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/0x1911f72C1cA2ff86729f159b6d570Ff6E197CaE9/sources/browser/SportsBettingToken.sol | 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./ | 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);
}
| 658,181 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view 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 ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view 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());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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 EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// 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 (last updated v4.5.0) (utils/math/Math.sol)
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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
/**
* @dev Flash-loan recipient interface
*/
interface IFlashLoanRecipient {
/**
* @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
*/
function onFlashLoan(
address caller,
IERC20 erc20Token,
uint256 amount,
uint256 feeAmount,
bytes memory data
) external;
}
/**
* @dev Bancor Network interface
*/
interface IBancorNetwork is IUpgradeable {
/**
* @dev returns the set of all valid pool collections
*/
function poolCollections() external view returns (IPoolCollection[] memory);
/**
* @dev returns the most recent collection that was added to the pool collections set for a specific type
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection);
/**
* @dev returns the set of all liquidity pools
*/
function liquidityPools() external view returns (Token[] memory);
/**
* @dev returns the respective pool collection for the provided pool
*/
function collectionByPool(Token pool) external view returns (IPoolCollection);
/**
* @dev returns whether the pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev creates a new pool
*
* requirements:
*
* - the pool doesn't already exist
*/
function createPool(uint16 poolType, Token token) external;
/**
* @dev creates new pools
*
* requirements:
*
* - none of the pools already exists
*/
function createPools(uint16 poolType, Token[] calldata tokens) external;
/**
* @dev migrates a list of pools between pool collections
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*/
function migratePools(Token[] calldata pools) external;
/**
* @dev deposits liquidity for the specified provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
) external payable returns (uint256);
/**
* @dev deposits liquidity for the current provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request and returns the respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the
* respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must have approved the contract to transfer the pool token amount on its behalf
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);
/**
* @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(uint256 id) external;
/**
* @dev withdraws liquidity and returns the withdrawn amount
*
* requirements:
*
* - the provider must have already initiated a withdrawal and received the specified id
* - the specified withdrawal request is eligible for completion
* - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT
* liquidity
*/
function withdraw(uint256 id) external returns (uint256);
/**
* @dev performs a trade by providing the input source amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an
* EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev performs a trade by providing the output target amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an
* EIP2612 permit request and returns the target amount and fee
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev provides a flash-loan
*
* requirements:
*
* - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
) external;
/**
* @dev deposits liquidity during a migration
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable;
/**
* @dev withdraws pending network fees
*
* requirements:
*
* - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
*/
function withdrawNetworkFees(address recipient) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
error NotWhitelisted();
struct VortexRewards {
// the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
uint32 burnRewardPPM;
// the maximum burn reward to be sent to the initiator of the burning event
uint256 burnRewardMaxAmount;
}
/**
* @dev Network Settings interface
*/
interface INetworkSettings is IUpgradeable {
/**
* @dev returns the protected tokens whitelist
*/
function protectedTokenWhitelist() external view returns (Token[] memory);
/**
* @dev checks whether a given token is whitelisted
*/
function isTokenWhitelisted(Token pool) external view returns (bool);
/**
* @dev returns the BNT funding limit for a given pool
*/
function poolFundingLimit(Token pool) external view returns (uint256);
/**
* @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
*/
function minLiquidityForTrading() external view returns (uint256);
/**
* @dev returns the global network fee (in units of PPM)
*
* notes:
*
* - the network fee is a portion of the total fees from each pool
*/
function networkFeePPM() external view returns (uint32);
/**
* @dev returns the withdrawal fee (in units of PPM)
*/
function withdrawalFeePPM() external view returns (uint32);
/**
* @dev returns the default flash-loan fee (in units of PPM)
*/
function defaultFlashLoanFeePPM() external view returns (uint32);
/**
* @dev returns the flash-loan fee (in units of PPM) of a pool
*/
function flashLoanFeePPM(Token pool) external view returns (uint32);
/**
* @dev returns the vortex settings
*/
function vortexRewards() external view returns (VortexRewards memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "./IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IVault } from "../../vaults/interfaces/IVault.sol";
// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");
// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");
// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");
// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");
/**
* @dev BNT Pool interface
*/
interface IBNTPool is IVault {
/**
* @dev returns the BNT pool token contract
*/
function poolToken() external view returns (IPoolToken);
/**
* @dev returns the total staked BNT balance in the network
*/
function stakedBalance() external view returns (uint256);
/**
* @dev returns the current funding of given pool
*/
function currentPoolFunding(Token pool) external view returns (uint256);
/**
* @dev returns the available BNT funding for a given pool
*/
function availableFunding(Token pool) external view returns (uint256);
/**
* @dev converts the specified pool token amount to the underlying BNT amount
*/
function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying BNT amount to pool token amount
*/
function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);
/**
* @dev mints BNT to the recipient
*
* requirements:
*
* - the caller must have the ROLE_BNT_MANAGER role
*/
function mint(address recipient, uint256 bntAmount) external;
/**
* @dev burns BNT from the vault
*
* requirements:
*
* - the caller must have the ROLE_VAULT_MANAGER role
*/
function burnFromVault(uint256 bntAmount) external;
/**
* @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - BNT tokens must have been already deposited into the contract
*/
function depositFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
bool isMigrating,
uint256 originalVBNTAmount
) external returns (uint256);
/**
* @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
*
* requirements:
*
* - the caller must be the network contract
* - VBNT token must have been already deposited into the contract
*/
function withdraw(
bytes32 contextId,
address provider,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the withdrawn BNT amount
*/
function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev requests BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the request amount should be below the funding limit for a given pool
* - the average rate of the pool must not deviate too much from its spot rate
*/
function requestFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev renounces BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the average rate of the pool must not deviate too much from its spot rate
*/
function renounceFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(
Token pool,
uint256 feeAmount,
bool isTradeFee
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";
import { Token } from "../../token/Token.sol";
import { IPoolToken } from "./IPoolToken.sol";
struct PoolLiquidity {
uint128 bntTradingLiquidity; // the BNT trading liquidity
uint128 baseTokenTradingLiquidity; // the base token trading liquidity
uint256 stakedBalance; // the staked balance
}
struct AverageRate {
uint32 blockNumber;
Fraction112 rate;
}
struct Pool {
IPoolToken poolToken; // the pool token of the pool
uint32 tradingFeePPM; // the trading fee (in units of PPM)
bool tradingEnabled; // whether trading is enabled
bool depositingEnabled; // whether depositing is enabled
AverageRate averageRate; // the recent average rate
uint256 depositLimit; // the deposit limit
PoolLiquidity liquidity; // the overall liquidity in the pool
}
struct WithdrawalAmounts {
uint256 totalAmount;
uint256 baseTokenAmount;
uint256 bntAmount;
}
// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
struct TradeAmountAndFee {
uint256 amount; // the source/target amount (depending on the context) resulting from the trade
uint256 tradingFeeAmount; // the trading fee amount
uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}
/**
* @dev Pool Collection interface
*/
interface IPoolCollection is IVersioned {
/**
* @dev returns the type of the pool
*/
function poolType() external pure returns (uint16);
/**
* @dev returns the default trading fee (in units of PPM)
*/
function defaultTradingFeePPM() external view returns (uint32);
/**
* @dev returns all the pools which are managed by this pool collection
*/
function pools() external view returns (Token[] memory);
/**
* @dev returns the number of all the pools which are managed by this pool collection
*/
function poolCount() external view returns (uint256);
/**
* @dev returns whether a pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev returns specific pool's data
*/
function poolData(Token pool) external view returns (Pool memory);
/**
* @dev returns the overall liquidity in the pool
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);
/**
* @dev returns the pool token of the pool
*/
function poolToken(Token pool) external view returns (IPoolToken);
/**
* @dev converts the specified pool token amount to the underlying base token amount
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying base token amount to pool token amount
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256);
/**
* @dev creates a new pool
*
* requirements:
*
* - the caller must be the network contract
* - the pool should have been whitelisted
* - the pool isn't already defined in the collection
*/
function createPool(Token token) external;
/**
* @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - assumes that the base token has been already deposited in the vault
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external returns (uint256);
/**
* @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
*
* requirements:
*
* - the caller must be the network contract
* - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the amounts that would be returned if the position is currently withdrawn,
* along with the breakdown of the base token and the BNT compensation
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev returns the output amount and fee when trading by providing the source amount
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev returns the input amount and fee when trading by providing the target amount
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(Token pool, uint256 feeAmount) external;
/**
* @dev migrates a pool to this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolIn(Token pool, Pool calldata data) external;
/**
* @dev migrates a pool from this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { EnumerableSetUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { Utils, AccessDenied, DoesNotExist, AlreadyExists, InvalidParam } from "../utility/Utils.sol";
import { Time } from "../utility/Time.sol";
import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol";
import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol";
import { IPoolToken } from "../pools/interfaces/IPoolToken.sol";
import { IBNTPool } from "../pools/interfaces/IBNTPool.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary, Signature } from "../token/TokenLibrary.sol";
import { IExternalRewardsVault } from "../vaults/interfaces/IExternalRewardsVault.sol";
import { IStandardRewards, ProgramData, Rewards, ProviderRewards, StakeAmounts } from "./interfaces/IStandardRewards.sol";
/**
* @dev Standard Rewards contract
*/
contract StandardRewards is IStandardRewards, ReentrancyGuardUpgradeable, Utils, Time, Upgradeable {
using Address for address payable;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using TokenLibrary for Token;
using SafeERC20 for IERC20;
struct RewardData {
Token rewardsToken;
uint256 amount;
}
struct ClaimData {
uint256 reward;
uint256 stakedAmount;
}
error ArrayNotUnique();
error InsufficientFunds();
error RewardsTooHigh();
error NativeTokenAmountMismatch();
error PoolMismatch();
error ProgramDisabled();
error ProgramInactive();
error RewardsTokenMismatch();
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In
// order to avoid this imprecision, we will amplify the reward rate by the units amount.
uint256 private constant REWARD_RATE_FACTOR = 1e18;
uint256 private constant INITIAL_PROGRAM_ID = 1;
// the network contract
IBancorNetwork private immutable _network;
// the network settings contract
INetworkSettings private immutable _networkSettings;
// the address of the BNT token governance
ITokenGovernance internal immutable _bntGovernance;
// the BNT contract
IERC20 private immutable _bnt;
// the VBNT contract
IERC20 private immutable _vbnt;
// the BNT pool token contract
IPoolToken private immutable _bntPoolToken;
// the address of the external rewards vault
IExternalRewardsVault private immutable _externalRewardsVault;
// the ID of the next created program
uint256 internal _nextProgramId;
// a mapping between providers and the program IDs of the program they are participating in
mapping(address => EnumerableSetUpgradeable.UintSet) private _programIdsByProvider;
// a mapping between program IDs and program data
mapping(uint256 => ProgramData) internal _programs;
// a mapping between pools and their latest programs
mapping(Token => uint256) private _latestProgramIdByPool;
// a mapping between programs and their respective rewards data
mapping(uint256 => Rewards) internal _programRewards;
// a mapping between providers, programs and their respective rewards data
mapping(address => mapping(uint256 => ProviderRewards)) internal _providerRewards;
// a mapping between programs and their total stakes
mapping(uint256 => uint256) private _programStakes;
// a mapping between reward tokens and total unclaimed rewards
mapping(Token => uint256) internal _unclaimedRewards;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 8] private __gap;
/**
* @dev triggered when a program is created
*/
event ProgramCreated(
Token indexed pool,
uint256 indexed programId,
Token indexed rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
);
/**
* @dev triggered when a program is terminated prematurely
*/
event ProgramTerminated(Token indexed pool, uint256 indexed programId, uint32 endTime, uint256 remainingRewards);
/**
* @dev triggered when a program is enabled/disabled
*/
event ProgramEnabled(Token indexed pool, uint256 indexed programId, bool status, uint256 remainingRewards);
/**
* @dev triggered when a provider joins a program
*/
event ProviderJoined(
Token indexed pool,
uint256 indexed programId,
address indexed provider,
uint256 poolTokenAmount,
uint256 prevStake
);
/**
* @dev triggered when a provider leaves a program (even if partially)
*/
event ProviderLeft(
Token indexed pool,
uint256 indexed programId,
address indexed provider,
uint256 poolTokenAmount,
uint256 remainingStake
);
/**
* @dev triggered when pending rewards are being claimed
*/
event RewardsClaimed(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount);
/**
* @dev triggered when pending rewards are being staked
*/
event RewardsStaked(Token indexed pool, uint256 indexed programId, address indexed provider, uint256 amount);
/**
* @dev a "virtual" constructor that is only used to set immutable state variables
*/
constructor(
IBancorNetwork initNetwork,
INetworkSettings initNetworkSettings,
ITokenGovernance initBNTGovernance,
IERC20 initVBNT,
IBNTPool initBNTPool,
IExternalRewardsVault initExternalRewardsVault
)
validAddress(address(initNetwork))
validAddress(address(initNetworkSettings))
validAddress(address(initBNTGovernance))
validAddress(address(initVBNT))
validAddress(address(initBNTPool))
validAddress(address(initExternalRewardsVault))
{
_network = initNetwork;
_networkSettings = initNetworkSettings;
_bntGovernance = initBNTGovernance;
_bnt = initBNTGovernance.token();
_vbnt = initVBNT;
_bntPoolToken = initBNTPool.poolToken();
_externalRewardsVault = initExternalRewardsVault;
}
/**
* @dev fully initializes the contract and its parents
*/
function initialize() external initializer {
__StandardRewards_init();
}
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __StandardRewards_init() internal onlyInitializing {
__ReentrancyGuard_init();
__Upgradeable_init();
__StandardRewards_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __StandardRewards_init_unchained() internal onlyInitializing {
_nextProgramId = INITIAL_PROGRAM_ID;
}
// solhint-enable func-name-mixedcase
modifier uniqueArray(uint256[] calldata ids) {
if (!_isArrayUnique(ids)) {
revert ArrayNotUnique();
}
_;
}
/**
* @dev authorize the contract to receive the native token
*/
receive() external payable {}
/**
* @inheritdoc Upgradeable
*/
function version() public pure override(IVersioned, Upgradeable) returns (uint16) {
return 3;
}
/**
* @inheritdoc IStandardRewards
*/
function programIds() external view returns (uint256[] memory) {
uint256 length = _nextProgramId - INITIAL_PROGRAM_ID;
uint256[] memory ids = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
ids[i] = i + INITIAL_PROGRAM_ID;
}
return ids;
}
/**
* @inheritdoc IStandardRewards
*/
function programs(uint256[] calldata ids) external view uniqueArray(ids) returns (ProgramData[] memory) {
uint256 length = ids.length;
ProgramData[] memory list = new ProgramData[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = _programs[ids[i]];
}
return list;
}
/**
* @inheritdoc IStandardRewards
*/
function providerProgramIds(address provider) external view returns (uint256[] memory) {
return _programIdsByProvider[provider].values();
}
/**
* @inheritdoc IStandardRewards
*/
function programRewards(uint256 id) external view returns (Rewards memory) {
return _programRewards[id];
}
/**
* @inheritdoc IStandardRewards
*/
function providerRewards(address provider, uint256 id) external view returns (ProviderRewards memory) {
return _providerRewards[provider][id];
}
/**
* @inheritdoc IStandardRewards
*/
function programStake(uint256 id) external view returns (uint256) {
return _programStakes[id];
}
/**
* @inheritdoc IStandardRewards
*/
function providerStake(address provider, uint256 id) external view returns (uint256) {
return _providerRewards[provider][id].stakedAmount;
}
/**
* @inheritdoc IStandardRewards
*/
function isProgramActive(uint256 id) external view returns (bool) {
return _isProgramActive(_programs[id]);
}
/**
* @inheritdoc IStandardRewards
*/
function isProgramEnabled(uint256 id) external view returns (bool) {
return _isProgramEnabled(_programs[id]);
}
/**
* @inheritdoc IStandardRewards
*/
function latestProgramId(Token pool) external view returns (uint256) {
return _latestProgramIdByPool[pool];
}
/**
* @inheritdoc IStandardRewards
*/
function createProgram(
Token pool,
Token rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
)
external
validAddress(address(pool))
validAddress(address(rewardsToken))
greaterThanZero(totalRewards)
onlyAdmin
nonReentrant
returns (uint256)
{
if (!(_time() <= startTime && startTime < endTime)) {
revert InvalidParam();
}
// ensure that no program exists for the specific pool
if (_isProgramActive(_programs[_latestProgramIdByPool[pool]])) {
revert AlreadyExists();
}
IPoolToken poolToken;
if (pool.isEqual(_bnt)) {
poolToken = _bntPoolToken;
} else {
if (!_networkSettings.isTokenWhitelisted(pool)) {
revert NotWhitelisted();
}
poolToken = _network.collectionByPool(pool).poolToken(pool);
}
// ensure that the rewards were already deposited to the rewards vault
uint256 unclaimedRewards = _unclaimedRewards[rewardsToken];
if (!rewardsToken.isEqual(_bnt)) {
if (rewardsToken.balanceOf(address(_externalRewardsVault)) < unclaimedRewards + totalRewards) {
revert InsufficientFunds();
}
}
uint256 id = _nextProgramId++;
uint256 rewardRate = totalRewards / (endTime - startTime);
_programs[id] = ProgramData({
id: id,
pool: pool,
poolToken: poolToken,
rewardsToken: rewardsToken,
isEnabled: true,
startTime: startTime,
endTime: endTime,
rewardRate: rewardRate,
remainingRewards: rewardRate * (endTime - startTime)
});
// set the program as the latest program of the pool
_latestProgramIdByPool[pool] = id;
// increase the unclaimed rewards for the token by the total rewards in the new program
_unclaimedRewards[rewardsToken] = unclaimedRewards + totalRewards;
emit ProgramCreated({
pool: pool,
programId: id,
rewardsToken: rewardsToken,
totalRewards: totalRewards,
startTime: startTime,
endTime: endTime
});
return id;
}
/**
* @inheritdoc IStandardRewards
*/
function terminateProgram(uint256 id) external onlyAdmin {
ProgramData memory p = _programs[id];
_verifyProgramActive(p);
// unset the program from being the latest program of the pool
delete _latestProgramIdByPool[p.pool];
// reduce the unclaimed rewards for the token by the remaining rewards
uint256 remainingRewards = _remainingRewards(p);
_unclaimedRewards[p.rewardsToken] -= remainingRewards;
// stop rewards accumulation
_programs[id].endTime = _time();
emit ProgramTerminated(p.pool, id, p.endTime, remainingRewards);
}
/**
* @inheritdoc IStandardRewards
*/
function enableProgram(uint256 id, bool status) external onlyAdmin {
ProgramData storage p = _programs[id];
_verifyProgramExists(p);
bool prevStatus = p.isEnabled;
if (prevStatus == status) {
return;
}
p.isEnabled = status;
emit ProgramEnabled({ pool: p.pool, programId: id, status: status, remainingRewards: _remainingRewards(p) });
}
/**
* @inheritdoc IStandardRewards
*/
function join(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
_join(msg.sender, p, poolTokenAmount, msg.sender);
}
/**
* @inheritdoc IStandardRewards
*/
function joinPermitted(
uint256 id,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
// permit the amount the caller is trying to stake. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner transferFrom will revert
p.poolToken.permit(msg.sender, address(this), poolTokenAmount, deadline, v, r, s);
_join(msg.sender, p, poolTokenAmount, msg.sender);
}
/**
* @inheritdoc IStandardRewards
*/
function leave(uint256 id, uint256 poolTokenAmount) external greaterThanZero(poolTokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramExists(p);
_leave(msg.sender, p, poolTokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function depositAndJoin(uint256 id, uint256 tokenAmount)
external
payable
greaterThanZero(tokenAmount)
nonReentrant
{
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
_depositAndJoin(msg.sender, p, tokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function depositAndJoinPermitted(
uint256 id,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external greaterThanZero(tokenAmount) nonReentrant {
ProgramData memory p = _programs[id];
_verifyProgramActiveAndEnabled(p);
p.pool.permit(msg.sender, address(this), tokenAmount, deadline, Signature({ v: v, r: r, s: s }));
_depositAndJoin(msg.sender, p, tokenAmount);
}
/**
* @inheritdoc IStandardRewards
*/
function pendingRewards(address provider, uint256[] calldata ids) external view uniqueArray(ids) returns (uint256) {
uint256 reward = 0;
Token rewardsToken;
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
ProgramData memory p = _programs[id];
_verifyProgramExists(p);
if (i == 0) {
rewardsToken = p.rewardsToken;
}
if (p.rewardsToken != rewardsToken) {
revert RewardsTokenMismatch();
}
uint256 newRewardPerToken = _rewardPerToken(p, _programRewards[id]);
ProviderRewards memory providerRewardsData = _providerRewards[provider][id];
reward += _pendingRewards(newRewardPerToken, providerRewardsData);
}
return reward;
}
/**
* @inheritdoc IStandardRewards
*/
function claimRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (uint256) {
RewardData memory rewardData = _claimRewards(msg.sender, ids, false);
if (rewardData.amount == 0) {
return 0;
}
_distributeRewards(msg.sender, rewardData);
return rewardData.amount;
}
/**
* @inheritdoc IStandardRewards
*/
function stakeRewards(uint256[] calldata ids) external uniqueArray(ids) nonReentrant returns (StakeAmounts memory) {
RewardData memory rewardData = _claimRewards(msg.sender, ids, true);
if (rewardData.amount == 0) {
return StakeAmounts({ stakedRewardAmount: 0, poolTokenAmount: 0 });
}
_distributeRewards(address(this), rewardData);
// deposit provider's tokens to the network. Please note, that since we're staking rewards, then the deposit
// should come from the contract itself, but the pool tokens should be sent to the provider directly
uint256 poolTokenAmount = _deposit(
msg.sender,
address(this),
false,
rewardData.rewardsToken,
rewardData.amount
);
return StakeAmounts({ stakedRewardAmount: rewardData.amount, poolTokenAmount: poolTokenAmount });
}
/**
* @dev transfers provider vBNT tokens to their owners (beta utility only, will be removed before the official launch)
*/
function transferProviderVBNT(address[] calldata providers, uint256[] calldata amounts) external onlyAdmin {
uint256 length = providers.length;
if (length != amounts.length) {
revert InvalidParam();
}
for (uint256 i = 0; i < length; i++) {
_vbnt.safeTransfer(providers[i], amounts[i]);
}
}
/**
* @dev adds provider's stake to the program
*/
function _join(
address provider,
ProgramData memory p,
uint256 poolTokenAmount,
address payer
) private {
// take a snapshot of the existing rewards (before increasing the stake)
ProviderRewards storage data = _snapshotRewards(p, provider);
// update both program and provider stakes
_programStakes[p.id] += poolTokenAmount;
uint256 prevStake = data.stakedAmount;
data.stakedAmount = prevStake + poolTokenAmount;
// unless the payer is the contract itself (in which case, no additional transfer is required), transfer the
// tokens from the payer (we aren't using safeTransferFrom, since the PoolToken is a fully compliant ERC20 token
// contract)
if (payer != address(this)) {
p.poolToken.transferFrom(payer, address(this), poolTokenAmount);
}
// add the program to the provider's program list
_programIdsByProvider[provider].add(p.id);
emit ProviderJoined({
pool: p.pool,
programId: p.id,
provider: provider,
poolTokenAmount: poolTokenAmount,
prevStake: prevStake
});
}
/**
* @dev removes (some of) provider's stake from the program
*/
function _leave(
address provider,
ProgramData memory p,
uint256 poolTokenAmount
) private {
// take a snapshot of the existing rewards (before decreasing the stake)
ProviderRewards storage data = _snapshotRewards(p, provider);
// update both program and provider stakes
_programStakes[p.id] -= poolTokenAmount;
uint256 remainingStake = data.stakedAmount - poolTokenAmount;
data.stakedAmount = remainingStake;
// transfer the tokens to the provider (we aren't using safeTransfer, since the PoolToken is a fully
// compliant ERC20 token contract)
p.poolToken.transfer(provider, poolTokenAmount);
// if the provider has removed all of its stake and there are no pending rewards - remove the program from the
// provider's program list
if (remainingStake == 0 && data.pendingRewards == 0) {
_programIdsByProvider[provider].remove(p.id);
}
emit ProviderLeft({
pool: p.pool,
programId: p.id,
provider: provider,
poolTokenAmount: poolTokenAmount,
remainingStake: remainingStake
});
}
/**
* @dev deposits provider's stake to the network and returns the received pool token amount
*/
function _deposit(
address provider,
address payer,
bool keepPoolTokens,
Token pool,
uint256 tokenAmount
) private returns (uint256) {
uint256 poolTokenAmount;
address recipient = keepPoolTokens ? address(this) : provider;
bool externalPayer = payer != address(this);
if (pool.isNative()) {
// unless the payer is the contract itself (e.g., during the staking process), in which case the native token
// was already claimed and pending in the contract - verify and use the received native token from the sender
if (externalPayer) {
if (msg.value < tokenAmount) {
revert NativeTokenAmountMismatch();
}
}
poolTokenAmount = _network.depositFor{ value: tokenAmount }(recipient, pool, tokenAmount);
// refund the caller for the remaining native token amount
if (externalPayer && msg.value > tokenAmount) {
payable(address(payer)).sendValue(msg.value - tokenAmount);
}
} else {
if (msg.value > 0) {
revert NativeTokenAmountMismatch();
}
// unless the payer is the contract itself (e.g., during the staking process), in which case the tokens were
// already claimed and pending in the contract - get the tokens from the provider
if (externalPayer) {
pool.safeTransferFrom(payer, address(this), tokenAmount);
}
pool.ensureApprove(address(_network), tokenAmount);
poolTokenAmount = _network.depositFor(recipient, pool, tokenAmount);
if (keepPoolTokens && pool.isEqual(_bnt)) {
_vbnt.safeTransfer(provider, poolTokenAmount);
}
}
return poolTokenAmount;
}
/**
* @dev deposits and adds provider's stake to the program
*/
function _depositAndJoin(
address provider,
ProgramData memory p,
uint256 tokenAmount
) private {
// deposit provider's tokens to the network and let the contract itself to claim the pool tokens so that it can
// immediately add them to a program
uint256 poolTokenAmount = _deposit(provider, provider, true, p.pool, tokenAmount);
// join the existing program, but ensure not to attempt to transfer the tokens from the provider by setting the
// payer as the contract itself
_join(provider, p, poolTokenAmount, address(this));
}
/**
* @dev claims rewards
*/
function _claimRewards(
address provider,
uint256[] calldata ids,
bool stake
) private returns (RewardData memory) {
RewardData memory rewardData = RewardData({ rewardsToken: Token(address(0)), amount: 0 });
for (uint256 i = 0; i < ids.length; i++) {
ProgramData memory p = _programs[ids[i]];
_verifyProgramEnabled(p);
if (i == 0) {
rewardData.rewardsToken = p.rewardsToken;
}
if (p.rewardsToken != rewardData.rewardsToken) {
revert RewardsTokenMismatch();
}
ClaimData memory claimData = _claimRewards(provider, p);
if (claimData.reward > 0) {
uint256 remainingRewards = p.remainingRewards;
// a sanity check that the reward amount doesn't exceed the remaining rewards per program
if (remainingRewards < claimData.reward) {
revert RewardsTooHigh();
}
// decrease the remaining rewards per program
_programs[ids[i]].remainingRewards = remainingRewards - claimData.reward;
// collect same-reward token rewards
rewardData.amount += claimData.reward;
}
// if the program is no longer active, has no stake left, and there are no pending rewards - remove the
// program from the provider's program list
if (!_isProgramActive(p) && claimData.stakedAmount == 0) {
_programIdsByProvider[provider].remove(p.id);
}
if (stake) {
emit RewardsStaked({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward });
} else {
emit RewardsClaimed({ pool: p.pool, programId: p.id, provider: provider, amount: claimData.reward });
}
}
// decrease the unclaimed rewards for the token by the total claimed rewards
_unclaimedRewards[rewardData.rewardsToken] -= rewardData.amount;
return rewardData;
}
/**
* @dev claims rewards and returns the received and the pending reward amounts
*/
function _claimRewards(address provider, ProgramData memory p) internal returns (ClaimData memory) {
ProviderRewards storage providerRewardsData = _snapshotRewards(p, provider);
uint256 reward = providerRewardsData.pendingRewards;
providerRewardsData.pendingRewards = 0;
return ClaimData({ reward: reward, stakedAmount: providerRewardsData.stakedAmount });
}
/**
* @dev returns whether the specified program is active
*/
function _isProgramActive(ProgramData memory p) private view returns (bool) {
uint32 currTime = _time();
return
_doesProgramExist(p) &&
p.startTime <= currTime &&
currTime <= p.endTime &&
_latestProgramIdByPool[p.pool] == p.id;
}
/**
* @dev returns whether the specified program is active
*/
function _isProgramEnabled(ProgramData memory p) private pure returns (bool) {
return p.isEnabled;
}
/**
* @dev returns whether or not a given program exists
*/
function _doesProgramExist(ProgramData memory p) private pure returns (bool) {
return address(p.pool) != address(0);
}
/**
* @dev verifies that a program exists
*/
function _verifyProgramExists(ProgramData memory p) private pure {
if (!_doesProgramExist(p)) {
revert DoesNotExist();
}
}
/**
* @dev verifies that a program exists, and active
*/
function _verifyProgramActive(ProgramData memory p) private view {
_verifyProgramExists(p);
if (!_isProgramActive(p)) {
revert ProgramInactive();
}
}
/**
* @dev verifies that a program is enabled
*/
function _verifyProgramEnabled(ProgramData memory p) private pure {
_verifyProgramExists(p);
if (!p.isEnabled) {
revert ProgramDisabled();
}
}
/**
* @dev verifies that a program exists, active, and enabled
*/
function _verifyProgramActiveAndEnabled(ProgramData memory p) private view {
_verifyProgramActive(p);
_verifyProgramEnabled(p);
}
/**
* @dev returns the remaining rewards of given program
*/
function _remainingRewards(ProgramData memory p) private view returns (uint256) {
uint32 currTime = _time();
return p.endTime > currTime ? p.rewardRate * (p.endTime - currTime) : 0;
}
/**
* @dev updates program and provider's rewards
*/
function _snapshotRewards(ProgramData memory p, address provider) private returns (ProviderRewards storage) {
Rewards storage rewards = _programRewards[p.id];
uint256 newRewardPerToken = _rewardPerToken(p, rewards);
if (newRewardPerToken != rewards.rewardPerToken) {
rewards.rewardPerToken = newRewardPerToken;
}
uint32 newUpdateTime = uint32(Math.min(_time(), p.endTime));
if (rewards.lastUpdateTime < newUpdateTime) {
rewards.lastUpdateTime = newUpdateTime;
}
ProviderRewards storage providerRewardsData = _providerRewards[provider][p.id];
uint256 newPendingRewards = _pendingRewards(newRewardPerToken, providerRewardsData);
if (newPendingRewards != 0) {
providerRewardsData.pendingRewards = newPendingRewards;
}
providerRewardsData.rewardPerTokenPaid = newRewardPerToken;
return providerRewardsData;
}
/**
* @dev calculates current reward per-token amount
*/
function _rewardPerToken(ProgramData memory p, Rewards memory rewards) private view returns (uint256) {
uint256 currTime = _time();
if (currTime < p.startTime) {
return 0;
}
uint256 totalStaked = _programStakes[p.id];
if (totalStaked == 0) {
return rewards.rewardPerToken;
}
uint256 stakingEndTime = Math.min(currTime, p.endTime);
uint256 stakingStartTime = Math.max(p.startTime, rewards.lastUpdateTime);
return
rewards.rewardPerToken +
(((stakingEndTime - stakingStartTime) * p.rewardRate * REWARD_RATE_FACTOR) / totalStaked);
}
/**
* @dev calculates provider's pending rewards
*/
function _pendingRewards(uint256 updatedRewardPerToken, ProviderRewards memory providerRewardsData)
private
pure
returns (uint256)
{
return
providerRewardsData.pendingRewards +
(providerRewardsData.stakedAmount * (updatedRewardPerToken - providerRewardsData.rewardPerTokenPaid)) /
REWARD_RATE_FACTOR;
}
/**
* @dev distributes reward
*/
function _distributeRewards(address recipient, RewardData memory rewardData) private {
if (rewardData.rewardsToken.isEqual(_bnt)) {
_bntGovernance.mint(recipient, rewardData.amount);
} else {
_externalRewardsVault.withdrawFunds(rewardData.rewardsToken, payable(recipient), rewardData.amount);
}
}
/**
* @dev returns whether the specified array has duplicates
*/
function _isArrayUnique(uint256[] calldata ids) private pure returns (bool) {
for (uint256 i = 0; i < ids.length; i++) {
for (uint256 j = i + 1; j < ids.length; j++) {
if (ids[i] == ids[j]) {
return false;
}
}
}
return true;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
import { Token } from "../../token/Token.sol";
struct Rewards {
uint32 lastUpdateTime;
uint256 rewardPerToken;
}
struct ProgramData {
uint256 id;
Token pool;
IPoolToken poolToken;
Token rewardsToken;
bool isEnabled;
uint32 startTime;
uint32 endTime;
uint256 rewardRate;
uint256 remainingRewards;
}
struct ProviderRewards {
uint256 rewardPerTokenPaid;
uint256 pendingRewards;
uint256 reserved0;
uint256 stakedAmount;
}
struct StakeAmounts {
uint256 stakedRewardAmount;
uint256 poolTokenAmount;
}
interface IStandardRewards is IUpgradeable {
/**
* @dev returns all program ids
*/
function programIds() external view returns (uint256[] memory);
/**
* @dev returns program data for each specified program id
*/
function programs(uint256[] calldata ids) external view returns (ProgramData[] memory);
/**
* @dev returns all the program ids that the provider participates in
*/
function providerProgramIds(address provider) external view returns (uint256[] memory);
/**
* @dev returns program rewards
*/
function programRewards(uint256 id) external view returns (Rewards memory);
/**
* @dev returns provider rewards
*/
function providerRewards(address provider, uint256 id) external view returns (ProviderRewards memory);
/**
* @dev returns the total staked amount in a specific program
*/
function programStake(uint256 id) external view returns (uint256);
/**
* @dev returns the total staked amount of a specific provider in a specific program
*/
function providerStake(address provider, uint256 id) external view returns (uint256);
/**
* @dev returns whether the specified program is active
*/
function isProgramActive(uint256 id) external view returns (bool);
/**
* @dev returns whether the specified program is enabled
*/
function isProgramEnabled(uint256 id) external view returns (bool);
/**
* @dev returns the ID of the latest program for a given pool (or 0 if no program is currently set)
*/
function latestProgramId(Token pool) external view returns (uint256);
/**
* @dev creates a program for a pool and returns its ID
*
* requirements:
*
* - the caller must be the admin of the contract
* - the pool must not have an active program
* - if the rewards token isn't the BNT token, then the rewards must have been deposited to the rewards vault
*/
function createProgram(
Token pool,
Token rewardsToken,
uint256 totalRewards,
uint32 startTime,
uint32 endTime
) external returns (uint256);
/**
* @dev terminates a rewards program
*
* requirements:
*
* - the caller must be the admin of the contract
* - the program must exist and be the active program for its pool
*/
function terminateProgram(uint256 id) external;
/**
* @dev enables or disables a program
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function enableProgram(uint256 id, bool status) external;
/**
* @dev adds a provider to the program
*
* requirements:
*
* - the caller must have approved the contract to transfer pool tokens on its behalf
*/
function join(uint256 id, uint256 poolTokenAmount) external;
/**
* @dev adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function joinPermitted(
uint256 id,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev removes (some of) provider's stake from the program
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function leave(uint256 id, uint256 poolTokenAmount) external;
/**
* @dev deposits and adds provider's stake to the program
*
* requirements:
*
* - the caller must have approved the network contract to transfer the tokens its behalf (except for in the
* native token case)
*/
function depositAndJoin(uint256 id, uint256 tokenAmount) external payable;
/**
* @dev deposits and adds provider's stake to the program by providing an EIP712 typed signature for an EIP2612
* permit request
*
* requirements:
*
* - the caller must have specified a valid and unused EIP712 typed signature
*/
function depositAndJoinPermitted(
uint256 id,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev returns provider's pending rewards
*
* requirements:
*
* - the specified program ids array needs to consist from unique and existing program ids with the same reward
* token
*/
function pendingRewards(address provider, uint256[] calldata ids) external view returns (uint256);
/**
* @dev claims rewards and returns the claimed reward amount
*/
function claimRewards(uint256[] calldata ids) external returns (uint256);
/**
* @dev claims and stake rewards and returns the claimed reward amount and the received pool token amount
*
* requirements:
*
* - the specified program ids array needs to consist from unique and existing program ids with the same reward
* token
* - the rewards token must have been whitelisted with an existing pool
*/
function stakeRewards(uint256[] calldata ids) external returns (StakeAmounts memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
struct Fraction {
uint256 n;
uint256 d;
}
struct Fraction112 {
uint112 n;
uint112 d;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Fraction, Fraction112 } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";
// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
return Fraction({ n: 0, d: 1 });
}
// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
return Fraction112({ n: 0, d: 1 });
}
/**
* @dev this library provides a set of fraction operations
*/
library FractionLibrary {
/**
* @dev returns whether a standard fraction is valid
*/
function isValid(Fraction memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a standard fraction is positive
*/
function isPositive(Fraction memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev returns whether a 112-bit fraction is valid
*/
function isValid(Fraction112 memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a 112-bit fraction is positive
*/
function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev reduces a standard fraction to a 112-bit fraction
*/
function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);
return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
}
/**
* @dev expands a 112-bit fraction to a standard fraction
*/
function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
return Fraction({ n: fraction.n, d: fraction.d });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction } from "./Fraction.sol";
import { PPM_RESOLUTION } from "./Constants.sol";
uint256 constant ONE = 1 << 127;
struct Uint512 {
uint256 hi; // 256 most significant bits
uint256 lo; // 256 least significant bits
}
struct Sint256 {
uint256 value;
bool isNeg;
}
/**
* @dev this library provides a set of complex math operations
*/
library MathEx {
error Overflow();
/**
* @dev returns `e ^ f`, where `e` is Euler's number and `f` is the input exponent:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(ONE, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with reduced components
*/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
return Fraction({ n: fraction.n / scale, d: fraction.d / scale });
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev this contract abstracts the block timestamp in order to allow for more flexible control in tests
*/
contract Time {
/**
* @dev returns the current time
*/
function _time() internal view virtual returns (uint32) {
return uint32(block.timestamp);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import { IUpgradeable } from "./interfaces/IUpgradeable.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides common utilities for upgradeable contracts
*/
abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable {
error AlreadyInitialized();
// the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract
// upgrades
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
uint32 internal constant MAX_GAP = 50;
uint16 internal _initializations;
// upgrade forward-compatibility storage gap
uint256[MAX_GAP - 1] private __gap;
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract and its parents
*/
function __Upgradeable_init() internal onlyInitializing {
__AccessControl_init();
__Upgradeable_init_unchained();
}
/**
* @dev performs contract-specific initialization
*/
function __Upgradeable_init_unchained() internal onlyInitializing {
_initializations = 1;
// set up administrative roles
_setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);
// allow the deployer to initially be the admin of the contract
_setupRole(ROLE_ADMIN, msg.sender);
}
// solhint-enable func-name-mixedcase
modifier onlyAdmin() {
_hasRole(ROLE_ADMIN, msg.sender);
_;
}
modifier onlyRoleMember(bytes32 role) {
_hasRole(role, msg.sender);
_;
}
function version() public view virtual override returns (uint16);
/**
* @dev returns the admin role
*/
function roleAdmin() external pure returns (bytes32) {
return ROLE_ADMIN;
}
/**
* @dev performs post-upgrade initialization
*
* requirements:
*
* - this must can be called only once per-upgrade
*/
function postUpgrade(bytes calldata data) external {
uint16 initializations = _initializations + 1;
if (initializations != version()) {
revert AlreadyInitialized();
}
_initializations = initializations;
_postUpgrade(data);
}
/**
* @dev an optional post-upgrade callback that can be implemented by child contracts
*/
function _postUpgrade(
bytes calldata /* data */
) internal virtual {}
function _hasRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert AccessDenied();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IExternalRewardsVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");
interface IVault is IUpgradeable {
/**
* @dev triggered when tokens have been withdrawn from the vault
*/
event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);
/**
* @dev triggered when tokens have been burned from the vault
*/
event FundsBurned(Token indexed token, address indexed caller, uint256 amount);
/**
* @dev tells whether the vault accepts native token deposits
*/
function isPayable() external view returns (bool);
/**
* @dev withdraws funds held by the contract and sends them to an account
*/
function withdrawFunds(
Token token,
address payable target,
uint256 amount
) external;
/**
* @dev burns funds held by the contract
*/
function burn(Token token, uint256 amount) external;
} | initializes the contract and its parents/ | function __StandardRewards_init() internal onlyInitializing {
__ReentrancyGuard_init();
__Upgradeable_init();
__StandardRewards_init_unchained();
}
| 10,286,436 |
/* Attestation decode and validation */
/* AlphaWallet 2020 */
pragma solidity ^0.5.0;
import "https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol";
contract DerDecode {
address payable owner;
bytes1 constant BOOLEAN_TAG = bytes1(0x01);
bytes1 constant INTEGER_TAG = bytes1(0x02);
bytes1 constant BIT_STRING_TAG = bytes1(0x03);
bytes1 constant OCTET_STRING_TAG = bytes1(0x04);
bytes1 constant NULL_TAG = bytes1(0x05);
bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06);
bytes1 constant EXTERNAL_TAG = bytes1(0x08);
bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10
bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16
bytes1 constant SET_TAG = bytes1(0x11); // decimal 17
bytes1 constant SET_OF_TAG = bytes1(0x11);
bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18
bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19
bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20
bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21
bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22
bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23
bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24
bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25
bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26
bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27
bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28
bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30
bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12
bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28
uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content
uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID"));
uint256 constant AA = 0;
uint256 constant BB = 7;
uint256 constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant CURVE_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141;
event Value(uint256 indexed val);
event RtnStr(bytes val);
event RtnS(string val);
constructor() public
{
owner = msg.sender;
}
struct Length {
uint decodeIndex;
uint length;
}
struct Exponent {
bytes base;
bytes riddle;
bytes tPoint;
uint256 challenge;
}
struct OctetString {
uint decodeIndex;
bytes byteCode;
}
function decodeAttestation(bytes memory attestation) public view returns(bool)
{
Length memory len;
Exponent memory pok;
OctetString memory octet;
require(attestation[0] == (CONSTRUCTED_TAG | SEQUENCE_TAG));
len = decodeLength(attestation, 1);
octet.decodeIndex = len.decodeIndex;
//decode parts
octet = decodeOctetString(attestation, octet.decodeIndex);
pok.base = octet.byteCode;
octet = decodeOctetString(attestation, octet.decodeIndex);
pok.riddle = octet.byteCode;
octet = decodeOctetString(attestation, octet.decodeIndex);
pok.challenge = bytesToUint(octet.byteCode);
octet = decodeOctetString(attestation, octet.decodeIndex);
pok.tPoint = octet.byteCode;
//ideally we should expand the concat to take multiple args
bytes memory cArray = concat(pok.base, pok.riddle);
cArray = concat(cArray, pok.tPoint);
(uint256 x, uint256 y) = extractXYFromPoint(pok.base);
// Multiply base with challenge
(uint256 lhsX, uint256 lhsY) = EllipticCurve.ecMul(pok.challenge, x, y, AA, PP);
(x, y) = extractXYFromPoint(pok.riddle);
uint256 c = mapToInteger(cArray);
(uint256 rhsX, uint256 rhsY) = EllipticCurve.ecMul(c, x, y, AA, PP);
(x, y) = extractXYFromPoint(pok.tPoint);
(rhsX, rhsY) = EllipticCurve.ecAdd(rhsX, rhsY, x, y, AA, PP);
if (lhsX == rhsX && lhsY == rhsY)
{
return true;
}
else
{
return false;
}
}
function extractXYFromPoint(bytes memory data) internal pure returns (uint256 x, uint256 y)
{
require (data[0] == OCTET_STRING_TAG);
bytes memory s = new bytes(32);
bytes memory r = new bytes(32);
for (uint i = 0; i < 32; i++)
{
s[i] = data[i+1];
r[i] = data[i+33];
}
x = bytesToUint(s);
y = bytesToUint(r);
}
//TODO: optimise using assembly
function mapToBytes(string memory id, uint t) private pure returns(bytes memory b)
{
uint i;
bytes memory s = new bytes(32);
bytes memory idBytes = bytes(id);
b = new bytes(idBytes.length + 4);
assembly { mstore(add(s, 32), t) }
for (i = 0; i < 4; i++)
{
b[i] = s[(32 - 4 + i)];
}
for (i = 0; i < (idBytes.length); i++)
{
b[i+4] = idBytes[i];
}
}
//TODO: Check maths; validate that it is correct to add the field size if the hash is negative
function mapToInteger(bytes memory input) private pure returns(uint256 idNumU)
{
bytes32 idHash = keccak256(input);
int256 idNum = int256(bytes32ToUint(idHash));
if (idNum < 0) idNum = idNum + int256(PP);
idNumU = uint256(idNum) % PP;
idNumU = idNumU % CURVE_ORDER;
}
function decodeOctetString(bytes memory byteCode, uint decodeIndex) private pure returns(OctetString memory data)
{
data.decodeIndex = decodeIndex;
Length memory len;
require (byteCode[data.decodeIndex++] == OCTET_STRING_TAG);
len = decodeLength(byteCode, data.decodeIndex);
data.decodeIndex = len.decodeIndex;
//parse the octet string
data.byteCode = new bytes(len.length);
//TODO: re-code in assembly
for (uint i = 0; i < len.length; i++)
{
data.byteCode[i] = byteCode[data.decodeIndex++];
}
}
function toBytes(uint256 x, uint length) private pure returns (bytes memory b)
{
bytes memory s = new bytes(32);
b = new bytes(length);
assembly { mstore(add(s, 32), x) }
for (uint i = 0; i < length; i++)
{
b[i] = s[(32 - length + i)];
}
}
function bytesToUint(bytes memory b) private pure returns (uint256 number)
{
for(uint i = 0; i < b.length; i++)
{
number = number + uint(uint8(b[i]))*(2**(8*(b.length-(i+1))));
}
}
function bytes32ToUint(bytes32 b) private pure returns (uint256 number)
{
for(uint i = 0; i < 32; i++)
{
number = number + uint(uint8(b[i]))*(2**(8*(b.length-(i+1))));
}
}
function decodeLength(bytes memory byteCode, uint decodeIndex) private pure returns(Length memory)
{
uint codeLength = 1;
Length memory retVal;
retVal.length = 0;
retVal.decodeIndex = decodeIndex;
if ((byteCode[retVal.decodeIndex] & 0x80) == 0x80)
{
codeLength = uint8((byteCode[retVal.decodeIndex++] & 0x7f));
}
for (uint i = 0; i < codeLength; i++)
{
retVal.length |= uint(uint8(byteCode[retVal.decodeIndex++] & 0xFF)) << ((codeLength - i - 1) * 8);
}
return retVal;
}
function decodeDER(bytes memory byteCode) public view returns(uint256[] memory) //limit for decoded input is 32 bytes for first draft
{
uint256[] memory objCodes = new uint256[](40); //arbitrary limit for testing - handle up to 40 translation objects
Status memory data;
uint objCodeIndex = 0;
uint decodeIndex = 0;
uint length = byteCode.length;
//need decodeDERLength
//first get tag of next object
while (decodeIndex < (length - 2) && byteCode[decodeIndex] != 0)
{
//get tag
bytes1 tag = byteCode[decodeIndex++];
require((tag & 0x20) == 0); //assert primitive
require((tag & 0xC0) == 0); //assert universal type
if ((tag & 0x1f) == IA5_STRING_TAG)
{
objCodes[objCodeIndex++] = IA5_CODE;
data = decodeIA5String(byteCode, objCodes, objCodeIndex, decodeIndex);
objCodeIndex = data.objCodeIndex;
decodeIndex = data.decodeIndex;
}
else if ((tag & 0x1f) == OBJECT_IDENTIFIER_TAG)
{
objCodes[objCodeIndex++] = DEROBJ_CODE;
data = decodeObjectIdentifier(byteCode, objCodes, objCodeIndex, decodeIndex);
objCodeIndex = data.objCodeIndex;
decodeIndex = data.decodeIndex;
}
}
uint256[] memory objCodesComplete = new uint256[](objCodeIndex);
for (uint i = 0; i < objCodeIndex; i++) objCodesComplete[i] = objCodes[i];
return objCodesComplete;
}
function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
bytes32 store = 0;
for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8);
objCodes[objCodeIndex++] = uint256(store);
Status memory retVal;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
struct Status {
uint decodeIndex;
uint objCodeIndex;
}
function decodeObjectIdentifier(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
Status memory retVal;
//1. decode leading pair
uint subIDEndIndex = decodeIndex;
uint256 subId;
while ((byteCode[subIDEndIndex] & 0x80) == 0x80)
{
require(subIDEndIndex < byteCode.length);
subIDEndIndex++;
}
uint subidentifier = 0;
for (uint i = decodeIndex; i <= subIDEndIndex; i++)
{
subId = uint256(uint8(byteCode[i] & 0x7f)) << ((subIDEndIndex - i) * 7);
subidentifier |= subId;
}
if (subidentifier < 40)
{
objCodes[objCodeIndex++] = 0;
objCodes[objCodeIndex++] = subidentifier;
}
else if (subidentifier < 80)
{
objCodes[objCodeIndex++] = 1;
objCodes[objCodeIndex++] = subidentifier - 40;
}
else
{
objCodes[objCodeIndex++] = 2;
objCodes[objCodeIndex++] = subidentifier - 80;
}
subIDEndIndex++;
while (subIDEndIndex < (decodeIndex + length) && byteCode[subIDEndIndex] != 0)
{
subidentifier = 0;
uint256 subIDStartIndex = subIDEndIndex;
while ((byteCode[subIDEndIndex] & 0x80) == 0x80)
{
require(subIDEndIndex < byteCode.length);
subIDEndIndex++;
}
subidentifier = 0;
for (uint256 j = subIDStartIndex; j <= subIDEndIndex; j++)
{
subId = uint256(uint8(byteCode[j] & 0x7f)) << ((subIDEndIndex - j) * 7);
subidentifier |= subId;
}
objCodes[objCodeIndex++] = subidentifier;
subIDEndIndex++;
}
decodeIndex += length;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
function endContract() public payable
{
if(msg.sender == owner)
{
selfdestruct(owner);
}
else revert();
}
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
} | Get a location of some free memory and store it in tempBytes as Solidity does for memory variables. Store the length of the first bytes array at the beginning of the memory for tempBytes. Maintain a memory counter for the current write location in the temp bytes array by adding the 32 bytes for the array length to the starting location. Stop copying when the memory counter reaches the length of the first bytes array. Initialize a copy counter to the start of the _preBytes data, 32 bytes into its memory. Increase both counters by 32 bytes each iteration. Write the _preBytes data into the tempBytes memory 32 bytes at a time. | function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
mc := add(mc, 0x20)
cc := add(cc, 0x20)
mstore(mc, mload(cc))
}
mstore(tempBytes, add(length, mload(tempBytes)))
for {
let cc := add(_postBytes, 0x20)
mc := add(mc, 0x20)
cc := add(cc, 0x20)
mstore(mc, mload(cc))
}
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
))
}
return tempBytes;
}
| 13,116,632 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {Decimal} from "../external/Decimal.sol";
import {Constants} from "../Constants.sol";
import {OracleRef} from "./../refs/OracleRef.sol";
import {TribeRoles} from "./../core/TribeRoles.sol";
import {RateLimited} from "./../utils/RateLimited.sol";
import {IPCVDeposit, PCVDeposit} from "./../pcv/PCVDeposit.sol";
import {INonCustodialPSM} from "./INonCustodialPSM.sol";
import {GlobalRateLimitedMinter} from "./../utils/GlobalRateLimitedMinter.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @notice Peg Stability Module that holds no funds.
/// On a mint, it transfers all proceeds to a PCV Deposit
/// When funds are needed for a redemption, they are simply pulled from the PCV Deposit
contract NonCustodialPSM is
OracleRef,
RateLimited,
ReentrancyGuard,
INonCustodialPSM
{
using Decimal for Decimal.D256;
using SafeCast for *;
using SafeERC20 for IERC20;
/// @notice the fee in basis points for selling an asset into VOLT
uint256 public override mintFeeBasisPoints;
/// @notice the fee in basis points for buying the asset for VOLT
uint256 public override redeemFeeBasisPoints;
/// @notice the PCV deposit target to deposit and withdraw from
IPCVDeposit public override pcvDeposit;
/// @notice the token this PSM will exchange for VOLT
/// Must be a stable token pegged to $1
IERC20 public immutable override underlyingToken;
/// @notice Rate Limited Minter contract that will be called when VOLT needs to be minted
GlobalRateLimitedMinter public override rateLimitedMinter;
/// @notice the max mint and redeem fee in basis points
/// Governance cannot change the maximum fee
uint256 public immutable override MAX_FEE = 300;
/// @notice boolean switch that indicates whether redeeming is paused
bool public redeemPaused;
/// @notice boolean switch that indicates whether minting is paused
bool public mintPaused;
/// @notice struct for passing constructor parameters related to OracleRef
struct OracleParams {
address coreAddress;
address oracleAddress;
address backupOracle;
int256 decimalsNormalizer;
}
/// @notice struct for passing constructor parameters related to MultiRateLimited
struct RateLimitedParams {
uint256 maxRateLimitPerSecond;
uint256 rateLimitPerSecond;
uint256 bufferCap;
}
/// @notice struct for passing constructor parameters related to the non custodial PSM
struct PSMParams {
uint256 mintFeeBasisPoints;
uint256 redeemFeeBasisPoints;
IERC20 underlyingToken;
IPCVDeposit pcvDeposit;
GlobalRateLimitedMinter rateLimitedMinter;
}
/// @notice construct the non custodial PSM. Structs are used to prevent stack too deep errors
/// @param params oracle ref constructor data
/// @param rateLimitedParams rate limited constructor data
/// @param psmParams non custodial PSM constructor data
constructor(
OracleParams memory params,
RateLimitedParams memory rateLimitedParams,
PSMParams memory psmParams
)
OracleRef(
params.coreAddress,
params.oracleAddress,
params.backupOracle,
params.decimalsNormalizer,
true /// hardcode doInvert to true to allow swaps to work correctly
)
/// rate limited replenishable passes false as the last param as there can be no partial actions
RateLimited(
rateLimitedParams.maxRateLimitPerSecond,
rateLimitedParams.rateLimitPerSecond,
rateLimitedParams.bufferCap,
false
)
{
underlyingToken = psmParams.underlyingToken;
_setGlobalRateLimitedMinter(psmParams.rateLimitedMinter);
_setMintFee(psmParams.mintFeeBasisPoints);
_setRedeemFee(psmParams.redeemFeeBasisPoints);
_setPCVDeposit(psmParams.pcvDeposit);
}
// ----------- Mint & Redeem pausing modifiers -----------
/// @notice modifier that allows execution when redemptions are not paused
modifier whileRedemptionsNotPaused() {
require(!redeemPaused, "PegStabilityModule: Redeem paused");
_;
}
/// @notice modifier that allows execution when minting is not paused
modifier whileMintingNotPaused() {
require(!mintPaused, "PegStabilityModule: Minting paused");
_;
}
// ----------- Governor & Guardian only pausing api -----------
/// @notice set secondary pausable methods to paused
function pauseRedeem() external onlyGuardianOrGovernor {
redeemPaused = true;
emit RedemptionsPaused(msg.sender);
}
/// @notice set secondary pausable methods to unpaused
function unpauseRedeem() external onlyGuardianOrGovernor {
redeemPaused = false;
emit RedemptionsUnpaused(msg.sender);
}
/// @notice set secondary pausable methods to paused
function pauseMint() external onlyGuardianOrGovernor {
mintPaused = true;
emit MintingPaused(msg.sender);
}
/// @notice set secondary pausable methods to unpaused
function unpauseMint() external onlyGuardianOrGovernor {
mintPaused = false;
emit MintingUnpaused(msg.sender);
}
// ----------- Governor, psm admin and parameter admin only state changing api -----------
/// @notice set the mint fee vs oracle price in basis point terms
/// @param newMintFeeBasisPoints the new fee in basis points for minting
function setMintFee(uint256 newMintFeeBasisPoints)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PARAMETER_ADMIN)
{
_setMintFee(newMintFeeBasisPoints);
}
/// @notice set the redemption fee vs oracle price in basis point terms
/// @param newRedeemFeeBasisPoints the new fee in basis points for redemptions
function setRedeemFee(uint256 newRedeemFeeBasisPoints)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PARAMETER_ADMIN)
{
_setRedeemFee(newRedeemFeeBasisPoints);
}
/// @notice set the target for sending all PCV
/// @param newTarget new PCV Deposit target for this PSM
function setPCVDeposit(IPCVDeposit newTarget)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PSM_ADMIN_ROLE)
{
_setPCVDeposit(newTarget);
}
/// @notice set the target to call for VOLT minting
/// @param newMinter new Global Rate Limited Minter for this PSM
function setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
external
override
hasAnyOfTwoRoles(TribeRoles.GOVERNOR, TribeRoles.PSM_ADMIN_ROLE)
{
_setGlobalRateLimitedMinter(newMinter);
}
// ----------- PCV Controller only state changing api -----------
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) external override onlyPCVController {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
// ----------- Public State Changing API -----------
/// @notice function to redeem VOLT for an underlying asset
/// We do not burn VOLT; this allows the contract's balance of VOLT to be used before the buffer is used
/// In practice, this helps prevent artificial cycling of mint-burn cycles and prevents DOS attacks.
/// This function will deplete the buffer based on the amount of VOLT that is being redeemed.
/// @param to the destination address for proceeds
/// @param amountVoltIn the amount of VOLT to sell
/// @param minAmountOut the minimum amount out otherwise the TX will fail
function redeem(
address to,
uint256 amountVoltIn,
uint256 minAmountOut
)
external
virtual
override
nonReentrant
whenNotPaused
whileRedemptionsNotPaused
returns (uint256 amountOut)
{
_depleteBuffer(amountVoltIn); /// deplete buffer first to save gas on buffer exhaustion sad path
updateOracle();
amountOut = _getRedeemAmountOut(amountVoltIn);
require(
amountOut >= minAmountOut,
"PegStabilityModule: Redeem not enough out"
);
IERC20(volt()).safeTransferFrom(
msg.sender,
address(this),
amountVoltIn
);
pcvDeposit.withdraw(to, amountOut);
emit Redeem(to, amountVoltIn, amountOut);
}
/// @notice function to buy VOLT for an underlying asset that is pegged to $1
/// We first transfer any contract-owned VOLT, then mint the remaining if necessary
/// This function will replenish the buffer based on the amount of VOLT that is being sent out.
/// @param to the destination address for proceeds
/// @param amountIn the amount of external asset to sell to the PSM
/// @param minVoltAmountOut the minimum amount of VOLT out otherwise the TX will fail
function mint(
address to,
uint256 amountIn,
uint256 minVoltAmountOut
)
external
virtual
override
nonReentrant
whenNotPaused
whileMintingNotPaused
returns (uint256 amountVoltOut)
{
updateOracle();
amountVoltOut = _getMintAmountOut(amountIn);
require(
amountVoltOut >= minVoltAmountOut,
"PegStabilityModule: Mint not enough out"
);
underlyingToken.safeTransferFrom(
msg.sender,
address(pcvDeposit),
amountIn
);
pcvDeposit.deposit();
uint256 amountFeiToTransfer = Math.min(
volt().balanceOf(address(this)),
amountVoltOut
);
uint256 amountFeiToMint = amountVoltOut - amountFeiToTransfer;
if (amountFeiToTransfer != 0) {
IERC20(volt()).safeTransfer(to, amountFeiToTransfer);
}
if (amountFeiToMint != 0) {
rateLimitedMinter.mintVolt(to, amountFeiToMint);
}
_replenishBuffer(amountVoltOut);
emit Mint(to, amountIn, amountVoltOut);
}
// ----------- Public View-Only API ----------
/// @notice calculate the amount of VOLT out for a given `amountIn` of underlying
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
/// @param amountIn the amount of external asset to sell to the PSM
/// @return amountVoltOut the amount of VOLT received for the amountIn of external asset
function getMintAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountVoltOut)
{
amountVoltOut = _getMintAmountOut(amountIn);
}
/// @notice calculate the amount of underlying out for a given `amountVoltIn` of VOLT
/// First get oracle price of token
/// Then figure out how many dollars that amount in is worth by multiplying price * amount.
/// ensure decimals are normalized if on underlying they are not 18
/// @param amountVoltIn the amount of VOLT to redeem
/// @return amountTokenOut the amount of the external asset received in exchange for the amount of VOLT redeemed
function getRedeemAmountOut(uint256 amountVoltIn)
public
view
override
returns (uint256 amountTokenOut)
{
amountTokenOut = _getRedeemAmountOut(amountVoltIn);
}
/// @notice getter to return the maximum amount of VOLT that could be purchased at once
/// @return the maximum amount of VOLT available for purchase at once through this PSM
function getMaxMintAmountOut() external view override returns (uint256) {
return
volt().balanceOf(address(this)) +
rateLimitedMinter.individualBuffer(address(this));
}
// ----------- Internal Methods -----------
/// @notice helper function to get mint amount out based on current market prices
/// @dev will revert if price is outside of bounds and price bound PSM is being used
/// @param amountIn the amount of stable asset in
/// @return amountVoltOut the amount of VOLT received for the amountIn of stable assets
function _getMintAmountOut(uint256 amountIn)
internal
view
virtual
returns (uint256 amountVoltOut)
{
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
Decimal.D256 memory adjustedAmountIn = price.mul(amountIn);
amountVoltOut = adjustedAmountIn
.mul(Constants.BASIS_POINTS_GRANULARITY - mintFeeBasisPoints)
.div(Constants.BASIS_POINTS_GRANULARITY)
.asUint256();
}
/// @notice helper function to get redeem amount out based on current market prices
/// @dev will revert if price is outside of bounds and price bound PSM is being used
/// @param amountVoltIn the amount of VOLT to redeem
/// @return amountTokenOut the amount of the external asset received in exchange for the amount of VOLT redeemed
function _getRedeemAmountOut(uint256 amountVoltIn)
internal
view
virtual
returns (uint256 amountTokenOut)
{
Decimal.D256 memory price = readOracle();
_validatePriceRange(price);
/// get amount of VOLT being provided being redeemed after fees
Decimal.D256 memory adjustedAmountIn = Decimal.from(
(amountVoltIn *
(Constants.BASIS_POINTS_GRANULARITY - redeemFeeBasisPoints)) /
Constants.BASIS_POINTS_GRANULARITY
);
/// now turn the VOLT into the underlying token amounts
/// amount VOLT in / VOLT you receive for $1 = how much stable token to pay out
amountTokenOut = adjustedAmountIn.div(price).asUint256();
}
// ----------- Helper methods to change state -----------
/// @notice set the global rate limited minter this PSM calls to mint VOLT
/// @param newMinter the new minter contract that this PSM will reference
function _setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
internal
{
require(
address(newMinter) != address(0),
"PegStabilityModule: Invalid new GlobalRateLimitedMinter"
);
GlobalRateLimitedMinter oldMinter = rateLimitedMinter;
rateLimitedMinter = newMinter;
emit GlobalRateLimitedMinterUpdate(oldMinter, newMinter);
}
/// @notice set the mint fee vs oracle price in basis point terms
/// @param newMintFeeBasisPoints the new fee for minting in basis points
function _setMintFee(uint256 newMintFeeBasisPoints) internal {
require(
newMintFeeBasisPoints <= MAX_FEE,
"PegStabilityModule: Mint fee exceeds max fee"
);
uint256 _oldMintFee = mintFeeBasisPoints;
mintFeeBasisPoints = newMintFeeBasisPoints;
emit MintFeeUpdate(_oldMintFee, newMintFeeBasisPoints);
}
/// @notice internal helper function to set the redemption fee
/// @param newRedeemFeeBasisPoints the new fee for redemptions in basis points
function _setRedeemFee(uint256 newRedeemFeeBasisPoints) internal {
require(
newRedeemFeeBasisPoints <= MAX_FEE,
"PegStabilityModule: Redeem fee exceeds max fee"
);
uint256 _oldRedeemFee = redeemFeeBasisPoints;
redeemFeeBasisPoints = newRedeemFeeBasisPoints;
emit RedeemFeeUpdate(_oldRedeemFee, newRedeemFeeBasisPoints);
}
/// @notice helper function to set the PCV deposit
/// @param newPCVDeposit the new PCV deposit that this PSM will pull assets from and deposit assets into
function _setPCVDeposit(IPCVDeposit newPCVDeposit) internal {
require(
address(newPCVDeposit) != address(0),
"PegStabilityModule: Invalid new PCVDeposit"
);
require(
newPCVDeposit.balanceReportedIn() == address(underlyingToken),
"PegStabilityModule: Underlying token mismatch"
);
IPCVDeposit oldTarget = pcvDeposit;
pcvDeposit = newPCVDeposit;
emit PCVDepositUpdate(oldTarget, newPCVDeposit);
}
// ----------- Hooks -----------
/// @notice overriden function in the price bound PSM
function _validatePriceRange(Decimal.D256 memory price)
internal
view
virtual
{}
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.8.4;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero() internal pure returns (D256 memory) {
return D256({value: 0});
}
function one() internal pure returns (D256 memory) {
return D256({value: BASE});
}
function from(uint256 a) internal pure returns (D256 memory) {
return D256({value: a.mul(BASE)});
}
function ratio(uint256 a, uint256 b) internal pure returns (D256 memory) {
return D256({value: getPartial(a, BASE, b)});
}
// ============ Self Functions ============
function add(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.add(b.mul(BASE))});
}
function sub(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.sub(b.mul(BASE))});
}
function sub(
D256 memory self,
uint256 b,
string memory reason
) internal pure returns (D256 memory) {
return D256({value: self.value.sub(b.mul(BASE), reason)});
}
function mul(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.mul(b)});
}
function div(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.div(b)});
}
function pow(D256 memory self, uint256 b)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({value: self.value});
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.add(b.value)});
}
function sub(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: self.value.sub(b.value)});
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
) internal pure returns (D256 memory) {
return D256({value: self.value.sub(b.value, reason)});
}
function mul(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: getPartial(self.value, b.value, BASE)});
}
function div(D256 memory self, D256 memory b)
internal
pure
returns (D256 memory)
{
return D256({value: getPartial(self.value, BASE, b.value)});
}
function equals(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b)
internal
pure
returns (bool)
{
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
) private pure returns (uint256) {
return target.mul(numerator).div(denominator);
}
function compareTo(D256 memory a, D256 memory b)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IWETH} from "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol";
library Constants {
/// @notice the denominator for basis points granularity (10,000)
uint256 public constant BASIS_POINTS_GRANULARITY = 10_000;
/// @notice the denominator for basis points granularity (10,000) expressed as an int data type
int256 public constant BP_INT = int256(BASIS_POINTS_GRANULARITY);
uint256 public constant ONE_YEAR = 365.25 days;
int256 public constant ONE_YEAR_INT = int256(ONE_YEAR);
/// @notice WETH9 address
IWETH public constant WETH =
IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/// @notice USD stand-in address
address public constant USD = 0x1111111111111111111111111111111111111111;
/// @notice Wei per ETH, i.e. 10**18
uint256 public constant ETH_GRANULARITY = 1e18;
/// @notice number of decimals in ETH, 18
uint256 public constant ETH_DECIMALS = 18;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IOracleRef.sol";
import "./CoreRef.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Reference to an Oracle
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
using SafeCast for int256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice the backup oracle reference by the contract
IOracle public override backupOracle;
/// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer)
int256 public override decimalsNormalizer;
bool public override doInvert;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
/// @param _backupOracle backup oracle to reference
/// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary
/// @param _doInvert invert the oracle price if this flag is on
constructor(
address _core,
address _oracle,
address _backupOracle,
int256 _decimalsNormalizer,
bool _doInvert
) CoreRef(_core) {
_setOracle(_oracle);
if (_backupOracle != address(0) && _backupOracle != _oracle) {
_setBackupOracle(_backupOracle);
}
_setDoInvert(_doInvert);
_setDecimalsNormalizer(_decimalsNormalizer);
}
/// @notice sets the referenced oracle
/// @param newOracle the new oracle to reference
function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
/// @notice sets the flag for whether to invert or not
/// @param newDoInvert the new flag for whether to invert
function setDoInvert(bool newDoInvert) external override onlyGovernor {
_setDoInvert(newDoInvert);
}
/// @notice sets the new decimalsNormalizer
/// @param newDecimalsNormalizer the new decimalsNormalizer
function setDecimalsNormalizer(int256 newDecimalsNormalizer)
external
override
onlyGovernor
{
_setDecimalsNormalizer(newDecimalsNormalizer);
}
/// @notice sets the referenced backup oracle
/// @param newBackupOracle the new backup oracle to reference
function setBackupOracle(address newBackupOracle)
external
override
onlyGovernorOrAdmin
{
_setBackupOracle(newBackupOracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice updates the referenced oracle
function updateOracle() public override {
oracle.update();
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function readOracle() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
if (!valid && address(backupOracle) != address(0)) {
(_peg, valid) = backupOracle.read();
}
require(valid, "OracleRef: oracle invalid");
// Scale the oracle price by token decimals delta if necessary
uint256 scalingFactor;
if (decimalsNormalizer < 0) {
scalingFactor = 10**(-1 * decimalsNormalizer).toUint256();
_peg = _peg.div(scalingFactor);
} else {
scalingFactor = 10**decimalsNormalizer.toUint256();
_peg = _peg.mul(scalingFactor);
}
// Invert the oracle price if necessary
if (doInvert) {
_peg = invert(_peg);
}
return _peg;
}
function _setOracle(address newOracle) internal {
require(newOracle != address(0), "OracleRef: zero address");
address oldOracle = address(oracle);
oracle = IOracle(newOracle);
emit OracleUpdate(oldOracle, newOracle);
}
// Supports zero address if no backup
function _setBackupOracle(address newBackupOracle) internal {
address oldBackupOracle = address(backupOracle);
backupOracle = IOracle(newBackupOracle);
emit BackupOracleUpdate(oldBackupOracle, newBackupOracle);
}
function _setDoInvert(bool newDoInvert) internal {
bool oldDoInvert = doInvert;
doInvert = newDoInvert;
if (oldDoInvert != newDoInvert) {
_setDecimalsNormalizer(-1 * decimalsNormalizer);
}
emit InvertUpdate(oldDoInvert, newDoInvert);
}
function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal {
int256 oldDecimalsNormalizer = decimalsNormalizer;
decimalsNormalizer = newDecimalsNormalizer;
emit DecimalsNormalizerUpdate(
oldDecimalsNormalizer,
newDecimalsNormalizer
);
}
function _setDecimalsNormalizerFromToken(address token) internal {
int256 feiDecimals = 18;
int256 _decimalsNormalizer = feiDecimals -
int256(uint256(IERC20Metadata(token).decimals()));
if (doInvert) {
_decimalsNormalizer = -1 * _decimalsNormalizer;
}
_setDecimalsNormalizer(_decimalsNormalizer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
@title Tribe DAO ACL Roles
@notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO.
Roles are broken up into 3 categories:
* Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed.
* Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms
* Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs.
*/
library TribeRoles {
/*///////////////////////////////////////////////////////////////
Major Roles
//////////////////////////////////////////////////////////////*/
/// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality.
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
/// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
/// @notice the role which can arbitrarily move PCV in any size from any contract
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
/// @notice can mint FEI arbitrarily
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
/*///////////////////////////////////////////////////////////////
Admin Roles
//////////////////////////////////////////////////////////////*/
/// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE.
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
/// @notice manages the Collateralization Oracle as well as other protocol oracles.
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
/// @notice manages TribalChief incentives and related functionality.
bytes32 internal constant TRIBAL_CHIEF_ADMIN =
keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
/// @notice admin of PCVGuardian
bytes32 internal constant PCV_GUARDIAN_ADMIN =
keccak256("PCV_GUARDIAN_ADMIN_ROLE");
/// @notice admin of all Minor Roles
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
/// @notice admin of the Fuse protocol
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
/// @notice capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
/// @notice capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
/// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
/*///////////////////////////////////////////////////////////////
Minor Roles
//////////////////////////////////////////////////////////////*/
/// @notice capable of poking existing LBP auctions to exchange tokens.
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
/// @notice capable of engaging with Votium for voting incentives.
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
/// @notice capable of changing parameters within non-critical ranges
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
/// @notice capable of adding an address to multi rate limited
bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE");
/// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM
bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE");
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @title abstract contract for putting a rate limit on how fast a contract can perform an action e.g. Minting
/// @author Fei Protocol
abstract contract RateLimited is CoreRef {
/// @notice maximum rate limit per second governance can set for this contract
uint256 public immutable MAX_RATE_LIMIT_PER_SECOND;
/// @notice the rate per second for this contract
uint256 public rateLimitPerSecond;
/// @notice the last time the buffer was used by the contract
uint256 public lastBufferUsedTime;
/// @notice the cap of the buffer that can be used at once
uint256 public bufferCap;
/// @notice a flag for whether to allow partial actions to complete if the buffer is less than amount
bool public doPartialAction;
/// @notice the buffer at the timestamp of lastBufferUsedTime
uint256 public bufferStored;
event BufferUsed(uint256 amountUsed, uint256 bufferRemaining);
event BufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap);
event RateLimitPerSecondUpdate(
uint256 oldRateLimitPerSecond,
uint256 newRateLimitPerSecond
);
constructor(
uint256 _maxRateLimitPerSecond,
uint256 _rateLimitPerSecond,
uint256 _bufferCap,
bool _doPartialAction
) {
lastBufferUsedTime = block.timestamp;
_setBufferCap(_bufferCap);
bufferStored = _bufferCap;
require(
_rateLimitPerSecond <= _maxRateLimitPerSecond,
"RateLimited: rateLimitPerSecond too high"
);
_setRateLimitPerSecond(_rateLimitPerSecond);
MAX_RATE_LIMIT_PER_SECOND = _maxRateLimitPerSecond;
doPartialAction = _doPartialAction;
}
/// @notice set the rate limit per second
function setRateLimitPerSecond(uint256 newRateLimitPerSecond)
external
virtual
onlyGovernorOrAdmin
{
require(
newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"RateLimited: rateLimitPerSecond too high"
);
_updateBufferStored();
_setRateLimitPerSecond(newRateLimitPerSecond);
}
/// @notice set the buffer cap
function setBufferCap(uint256 newBufferCap)
external
virtual
onlyGovernorOrAdmin
{
_setBufferCap(newBufferCap);
}
/// @notice the amount of action used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
function buffer() public view returns (uint256) {
uint256 elapsed = block.timestamp - lastBufferUsedTime;
return
Math.min(bufferStored + (rateLimitPerSecond * elapsed), bufferCap);
}
/**
@notice the method that enforces the rate limit. Decreases buffer by "amount".
If buffer is <= amount either
1. Does a partial mint by the amount remaining in the buffer or
2. Reverts
Depending on whether doPartialAction is true or false
*/
function _depleteBuffer(uint256 amount) internal virtual returns (uint256) {
uint256 newBuffer = buffer();
uint256 usedAmount = amount;
if (doPartialAction && usedAmount > newBuffer) {
usedAmount = newBuffer;
}
require(newBuffer != 0, "RateLimited: no rate limit buffer");
require(usedAmount <= newBuffer, "RateLimited: rate limit hit");
bufferStored = newBuffer - usedAmount;
lastBufferUsedTime = block.timestamp;
emit BufferUsed(usedAmount, bufferStored);
return usedAmount;
}
/// @notice function to replenish buffer
/// @param amount to increase buffer by if under buffer cap
function _replenishBuffer(uint256 amount) internal {
uint256 newBuffer = buffer();
uint256 _bufferCap = bufferCap; /// gas opti, save an SLOAD
/// cannot replenish any further if already at buffer cap
if (newBuffer == _bufferCap) {
return;
}
/// ensure that bufferStored cannot be gt buffer cap
bufferStored = Math.min(newBuffer + amount, _bufferCap);
}
function _setRateLimitPerSecond(uint256 newRateLimitPerSecond) internal {
uint256 oldRateLimitPerSecond = rateLimitPerSecond;
rateLimitPerSecond = newRateLimitPerSecond;
emit RateLimitPerSecondUpdate(
oldRateLimitPerSecond,
newRateLimitPerSecond
);
}
function _setBufferCap(uint256 newBufferCap) internal {
_updateBufferStored();
uint256 oldBufferCap = bufferCap;
bufferCap = newBufferCap;
emit BufferCapUpdate(oldBufferCap, newBufferCap);
}
function _resetBuffer() internal {
bufferStored = bufferCap;
}
function _updateBufferStored() internal {
bufferStored = buffer();
lastBufferUsedTime = block.timestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "./IPCVDeposit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller
/// @author Fei Protocol
abstract contract PCVDeposit is IPCVDeposit, CoreRef {
using SafeERC20 for IERC20;
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) public virtual override onlyPCVController {
_withdrawERC20(token, to, amount);
}
function _withdrawERC20(
address token,
address to,
uint256 amount
) internal {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
/// @notice withdraw ETH from the contract
/// @param to address to send ETH
/// @param amountOut amount of ETH to send
function withdrawETH(address payable to, uint256 amountOut)
external
virtual
override
onlyPCVController
{
Address.sendValue(to, amountOut);
emit WithdrawETH(msg.sender, to, amountOut);
}
function balance() public view virtual override returns (uint256);
function resistantBalanceAndVolt()
public
view
virtual
override
returns (uint256, uint256)
{
return (balance(), 0);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPCVDeposit} from "../pcv/IPCVDeposit.sol";
import {GlobalRateLimitedMinter} from "../utils/GlobalRateLimitedMinter.sol";
/**
* @title Fei Peg Stability Module
* @author Fei Protocol
* @notice The Fei PSM is a contract which pulls reserve assets from PCV Deposits in order to exchange FEI at $1 of underlying assets with a fee.
* `mint()` - buy FEI for $1 of underlying tokens
* `redeem()` - sell FEI back for $1 of the same
*
*
* The contract is a
* OracleRef - to determine price of underlying, and
* RateLimitedReplenishable - to stop infinite mints and related DOS issues
*
* Inspired by MakerDAO PSM, code written without reference
*/
interface INonCustodialPSM {
// ----------- Public State Changing API -----------
/// @notice mint `amountFeiOut` FEI to address `to` for `amountIn` underlying tokens
/// @dev see getMintAmountOut() to pre-calculate amount out
function mint(
address to,
uint256 amountIn,
uint256 minAmountOut
) external returns (uint256 amountFeiOut);
/// @notice redeem `amountFeiIn` FEI for `amountOut` underlying tokens and send to address `to`
/// @dev see getRedeemAmountOut() to pre-calculate amount out
function redeem(
address to,
uint256 amountFeiIn,
uint256 minAmountOut
) external returns (uint256 amountOut);
// ----------- Governor or Admin Only State Changing API -----------
/// @notice set the mint fee vs oracle price in basis point terms
function setMintFee(uint256 newMintFeeBasisPoints) external;
/// @notice set the redemption fee vs oracle price in basis point terms
function setRedeemFee(uint256 newRedeemFeeBasisPoints) external;
/// @notice set the target for sending surplus reserves
function setPCVDeposit(IPCVDeposit newTarget) external;
/// @notice set the target to call for FEI minting
function setGlobalRateLimitedMinter(GlobalRateLimitedMinter newMinter)
external;
/// @notice withdraw ERC20 from the contract
function withdrawERC20(
address token,
address to,
uint256 amount
) external;
// ----------- Getters -----------
/// @notice calculate the amount of FEI out for a given `amountIn` of underlying
function getMintAmountOut(uint256 amountIn)
external
view
returns (uint256 amountFeiOut);
/// @notice calculate the amount of underlying out for a given `amountFeiIn` of FEI
function getRedeemAmountOut(uint256 amountFeiIn)
external
view
returns (uint256 amountOut);
/// @notice the maximum mint amount out
function getMaxMintAmountOut() external view returns (uint256);
/// @notice the mint fee vs oracle price in basis point terms
function mintFeeBasisPoints() external view returns (uint256);
/// @notice the redemption fee vs oracle price in basis point terms
function redeemFeeBasisPoints() external view returns (uint256);
/// @notice the underlying token exchanged for FEI
function underlyingToken() external view returns (IERC20);
/// @notice the PCV deposit target to deposit and withdraw from
function pcvDeposit() external view returns (IPCVDeposit);
/// @notice Rate Limited Minter contract that will be called when FEI needs to be minted
function rateLimitedMinter()
external
view
returns (GlobalRateLimitedMinter);
/// @notice the max mint and redeem fee in basis points
function MAX_FEE() external view returns (uint256);
// ----------- Events -----------
/// @notice event emitted when a new max fee is set
event MaxFeeUpdate(uint256 oldMaxFee, uint256 newMaxFee);
/// @notice event emitted when a new mint fee is set
event MintFeeUpdate(uint256 oldMintFee, uint256 newMintFee);
/// @notice event emitted when a new redeem fee is set
event RedeemFeeUpdate(uint256 oldRedeemFee, uint256 newRedeemFee);
/// @notice event emitted when reservesThreshold is updated
event ReservesThresholdUpdate(
uint256 oldReservesThreshold,
uint256 newReservesThreshold
);
/// @notice event emitted when surplus target is updated
event PCVDepositUpdate(IPCVDeposit oldTarget, IPCVDeposit newTarget);
/// @notice event emitted upon a redemption
event Redeem(address to, uint256 amountFeiIn, uint256 amountAssetOut);
/// @notice event emitted when fei gets minted
event Mint(address to, uint256 amountIn, uint256 amountFeiOut);
/// @notice event emitted when ERC20 tokens get withdrawn
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
/// @notice event emitted when global rate limited minter is updated
event GlobalRateLimitedMinterUpdate(
GlobalRateLimitedMinter oldMinter,
GlobalRateLimitedMinter newMinter
);
/// @notice event that is emitted when redemptions are paused
event RedemptionsPaused(address account);
/// @notice event that is emitted when redemptions are unpaused
event RedemptionsUnpaused(address account);
/// @notice event that is emitted when minting is paused
event MintingPaused(address account);
/// @notice event that is emitted when minting is unpaused
event MintingUnpaused(address account);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {MultiRateLimited} from "./MultiRateLimited.sol";
import {IGlobalRateLimitedMinter} from "./IGlobalRateLimitedMinter.sol";
import {CoreRef} from "./../refs/CoreRef.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice global contract to handle rate limited minting of VOLT on a global level
/// allows whitelisted minters to call in and specify the address to mint VOLT to within
/// that contract's limits
contract GlobalRateLimitedMinter is MultiRateLimited, IGlobalRateLimitedMinter {
/// @param coreAddress address of the core contract
/// @param _globalMaxRateLimitPerSecond maximum amount of VOLT that can replenish per second ever, this amount cannot be changed by governance
/// @param _perAddressRateLimitMaximum maximum rate limit per second per address
/// @param _maxRateLimitPerSecondPerAddress maximum rate limit per second per address in multi rate limited
/// @param _maxBufferCap maximum buffer cap in multi rate limited contract
/// @param _globalBufferCap maximum global buffer cap
constructor(
address coreAddress,
uint256 _globalMaxRateLimitPerSecond,
uint256 _perAddressRateLimitMaximum,
uint256 _maxRateLimitPerSecondPerAddress,
uint256 _maxBufferCap,
uint256 _globalBufferCap
)
CoreRef(coreAddress)
MultiRateLimited(
_globalMaxRateLimitPerSecond,
_perAddressRateLimitMaximum,
_maxRateLimitPerSecondPerAddress,
_maxBufferCap,
_globalBufferCap
)
{}
/// @notice mint VOLT to the target address and deplete the buffer
/// pausable and depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// @param amount the amount of VOLT to mint
function mintVolt(address to, uint256 amount)
external
virtual
override
whenNotPaused
{
_depleteIndividualBuffer(msg.sender, amount);
_mintVolt(to, amount);
}
/// @notice mint VOLT to the target address and deplete the whole rate limited
/// minter's buffer, pausable and completely depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// mints all VOLT that msg.sender has in the buffer
function mintMaxAllowableVolt(address to)
external
virtual
override
whenNotPaused
{
uint256 amount = Math.min(individualBuffer(msg.sender), buffer());
_depleteIndividualBuffer(msg.sender, amount);
_mintVolt(to, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
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 generally not needed starting with Solidity 0.8, since 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;
}
}
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Fei Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed oldOracle, address indexed newOracle);
event InvertUpdate(bool oldDoInvert, bool newDoInvert);
event DecimalsNormalizerUpdate(
int256 oldDecimalsNormalizer,
int256 newDecimalsNormalizer
);
event BackupOracleUpdate(
address indexed oldBackupOracle,
address indexed newBackupOracle
);
// ----------- State changing API -----------
function updateOracle() external;
// ----------- Governor only state changing API -----------
function setOracle(address newOracle) external;
function setBackupOracle(address newBackupOracle) external;
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external;
function setDoInvert(bool newDoInvert) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function backupOracle() external view returns (IOracle);
function doInvert() external view returns (bool);
function decimalsNormalizer() external view returns (int256);
function readOracle() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private immutable _core;
IVolt private immutable _volt;
IERC20 private immutable _vcon;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
constructor(address coreAddress) {
_core = ICore(coreAddress);
_volt = ICore(coreAddress).volt();
_vcon = ICore(coreAddress).vcon();
_setContractAdminRole(ICore(coreAddress).GOVERN_ROLE());
}
function _initialize() internal {} // no-op for backward compatibility
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) || isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) || _core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin"
);
_;
}
// Named onlyTribeRole to prevent collision with OZ onlyRole modifier
modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfThreeRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFourRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFiveRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4,
bytes32 role5
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender) ||
_core.hasRole(role5, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier onlyVolt() {
require(msg.sender == address(_volt), "CoreRef: Caller is not VOLT");
_;
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole)
external
override
onlyGovernor
{
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin)
public
view
override
returns (bool)
{
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function volt() public view override returns (IVolt) {
return _volt;
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function vcon() public view override returns (IERC20) {
return _vcon;
}
/// @notice volt balance of contract
/// @return volt amount held
function voltBalance() public view override returns (uint256) {
return _volt.balanceOf(address(this));
}
/// @notice vcon balance of contract
/// @return vcon amount held
function vconBalance() public view override returns (uint256) {
return _vcon.balanceOf(address(this));
}
function _burnVoltHeld() internal {
_volt.burn(voltBalance());
}
function _mintVolt(address to, uint256 amount) internal virtual {
if (amount != 0) {
_volt.mint(to, amount);
}
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(
oldContractAdminRole,
newContractAdminRole
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../external/Decimal.sol";
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external;
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(
bytes32 indexed oldContractAdminRole,
bytes32 indexed newContractAdminRole
);
// ----------- Governor only state changing api -----------
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function volt() external view returns (IVolt);
function vcon() external view returns (IERC20);
function voltBalance() external view returns (uint256);
function vconBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {IPermissions} from "./IPermissions.sol";
import {IVolt, IERC20} from "../volt/IVolt.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event VoltUpdate(IERC20 indexed _volt);
event VconUpdate(IERC20 indexed _vcon);
// ----------- Getters -----------
function volt() external view returns (IVolt);
function vcon() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IVolt is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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 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: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
// 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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPCVDepositBalances.sol";
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit is IPCVDepositBalances {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(
address token,
address to,
uint256 amount
) external;
function withdrawETH(address payable to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface for only balance getters
/// @author Fei Protocol
interface IPCVDepositBalances {
// ----------- Getters -----------
/// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn
function balance() external view returns (uint256);
/// @notice gets the token address in which this deposit returns its balance
function balanceReportedIn() external view returns (address);
/// @notice gets the resistant token balance and protocol owned fei of this deposit
function resistantBalanceAndVolt() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import {CoreRef} from "../refs/CoreRef.sol";
import {TribeRoles} from "./../core/TribeRoles.sol";
import {RateLimited} from "./RateLimited.sol";
import {IMultiRateLimited} from "./IMultiRateLimited.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title abstract contract for putting a rate limit on how fast an address can perform an action e.g. Minting
/// there are two buffers, one buffer which is each individual addresses's current buffer,
/// and then there is a global buffer which is the buffer that each individual address must respect as well
/// @author Elliot Friedman, Fei Protocol
/// this contract was made abstract so that other contracts that already construct an instance of CoreRef
/// do not collide with this one
abstract contract MultiRateLimited is RateLimited, IMultiRateLimited {
using SafeCast for *;
/// @notice the struct containing all information per rate limited address
struct RateLimitData {
uint32 lastBufferUsedTime;
uint112 bufferCap;
uint112 bufferStored;
uint112 rateLimitPerSecond;
}
/// @notice rate limited address information
mapping(address => RateLimitData) public rateLimitPerAddress;
/// @notice max rate limit per second allowable by non governor per contract
uint256 public individualMaxRateLimitPerSecond;
/// @notice max buffer cap allowable by non governor per contract
uint256 public individualMaxBufferCap;
/// @param _maxRateLimitPerSecond maximum amount of fei that can replenish per second ever, this amount cannot be changed by governance
/// @param _rateLimitPerSecond maximum rate limit per second per address
/// @param _individualMaxRateLimitPerSecond maximum rate limit per second per address in multi rate limited
/// @param _individualMaxBufferCap maximum buffer cap in multi rate limited
/// @param _globalBufferCap maximum global buffer cap
constructor(
uint256 _maxRateLimitPerSecond,
uint256 _rateLimitPerSecond,
uint256 _individualMaxRateLimitPerSecond,
uint256 _individualMaxBufferCap,
uint256 _globalBufferCap
)
RateLimited(
_maxRateLimitPerSecond,
_rateLimitPerSecond,
_globalBufferCap,
false
)
{
require(
_individualMaxBufferCap < _globalBufferCap,
"MultiRateLimited: max buffer cap invalid"
);
individualMaxRateLimitPerSecond = _individualMaxRateLimitPerSecond;
individualMaxBufferCap = _individualMaxBufferCap;
}
modifier addressIsRegistered(address rateLimitedAddress) {
require(
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime != 0,
"MultiRateLimited: rate limit address does not exist"
);
_;
}
// ----------- Governor and Admin only state changing api -----------
/// @notice update the ADD_MINTER_ROLE rate limit per second
/// @param newRateLimitPerSecond new maximum rate limit per second for add minter role
function updateMaxRateLimitPerSecond(uint256 newRateLimitPerSecond)
external
virtual
override
onlyGovernor
{
require(
newRateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: exceeds global max rate limit per second"
);
uint256 oldMaxRateLimitPerSecond = individualMaxRateLimitPerSecond;
individualMaxRateLimitPerSecond = newRateLimitPerSecond;
emit MultiMaxRateLimitPerSecondUpdate(
oldMaxRateLimitPerSecond,
newRateLimitPerSecond
);
}
/// @notice update the ADD_MINTER_ROLE max buffer cap
/// @param newBufferCap new buffer cap for ADD_MINTER_ROLE added addresses
function updateMaxBufferCap(uint256 newBufferCap)
external
virtual
override
onlyGovernor
{
require(
newBufferCap <= bufferCap,
"MultiRateLimited: exceeds global buffer cap"
);
uint256 oldBufferCap = individualMaxBufferCap;
individualMaxBufferCap = newBufferCap;
emit MultiBufferCapUpdate(oldBufferCap, newBufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// @param _rateLimitPerSecond the rate limit per second for this rateLimitedAddress
/// @param _bufferCap the buffer cap for this rateLimitedAddress
function addAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) external virtual override onlyGovernor {
_addAddress(rateLimitedAddress, _rateLimitPerSecond, _bufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the address whose buffer and rate limit per second will be set
/// @param _rateLimitPerSecond the new rate limit per second for this rateLimitedAddress
/// @param _bufferCap the new buffer cap for this rateLimitedAddress
function updateAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
)
external
virtual
override
addressIsRegistered(rateLimitedAddress)
hasAnyOfTwoRoles(TribeRoles.ADD_MINTER_ROLE, TribeRoles.GOVERNOR)
{
if (core().hasRole(TribeRoles.ADD_MINTER_ROLE, msg.sender)) {
require(
_rateLimitPerSecond <= individualMaxRateLimitPerSecond,
"MultiRateLimited: rate limit per second exceeds non governor allowable amount"
);
require(
_bufferCap <= individualMaxBufferCap,
"MultiRateLimited: max buffer cap exceeds non governor allowable amount"
);
}
require(
_bufferCap <= bufferCap,
"MultiRateLimited: buffercap too high"
);
_updateAddress(rateLimitedAddress, _rateLimitPerSecond, _bufferCap);
}
/// @notice add an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// gives the newly added contract the maximum allowable rate limit per second and buffer cap
function addAddressWithCaps(address rateLimitedAddress)
external
virtual
override
onlyTribeRole(TribeRoles.ADD_MINTER_ROLE)
{
_addAddress(
rateLimitedAddress,
uint112(individualMaxRateLimitPerSecond),
uint112(individualMaxBufferCap)
);
}
/// @notice remove an authorized rateLimitedAddress contract
/// @param rateLimitedAddress the address to remove from the whitelist of addresses
function removeAddress(address rateLimitedAddress)
external
virtual
override
addressIsRegistered(rateLimitedAddress)
onlyGuardianOrGovernor
{
uint256 oldRateLimitPerSecond = rateLimitPerAddress[rateLimitedAddress]
.rateLimitPerSecond;
delete rateLimitPerAddress[rateLimitedAddress];
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
oldRateLimitPerSecond,
0
);
}
// ----------- Getters -----------
/// @notice the amount of action used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
/// @param rateLimitedAddress the address whose buffer will be returned
/// @return the buffer of the specified rate limited address
function individualBuffer(address rateLimitedAddress)
public
view
override
returns (uint112)
{
RateLimitData memory rateLimitData = rateLimitPerAddress[
rateLimitedAddress
];
uint256 elapsed = block.timestamp - rateLimitData.lastBufferUsedTime;
return
uint112(
Math.min(
rateLimitData.bufferStored +
(rateLimitData.rateLimitPerSecond * elapsed),
rateLimitData.bufferCap
)
);
}
/// @notice the rate per second for each address
function getRateLimitPerSecond(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].rateLimitPerSecond;
}
/// @notice the last time the buffer was used by each address
function getLastBufferUsedTime(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].lastBufferUsedTime;
}
/// @notice the cap of the buffer that can be used at once
function getBufferCap(address limiter)
external
view
override
returns (uint256)
{
return rateLimitPerAddress[limiter].bufferCap;
}
// ----------- Helper Methods -----------
function _updateAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) internal {
RateLimitData storage rateLimitData = rateLimitPerAddress[
rateLimitedAddress
];
require(
rateLimitData.lastBufferUsedTime != 0,
"MultiRateLimited: rate limit address does not exist"
);
require(
_rateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: rateLimitPerSecond too high"
);
uint112 oldRateLimitPerSecond = rateLimitData.rateLimitPerSecond;
rateLimitData.lastBufferUsedTime = block.timestamp.toUint32();
rateLimitData.bufferCap = _bufferCap;
rateLimitData.rateLimitPerSecond = _rateLimitPerSecond;
rateLimitData.bufferStored = _bufferCap;
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
oldRateLimitPerSecond,
_rateLimitPerSecond
);
}
/// @param rateLimitedAddress the new address to add as a rateLimitedAddress
/// @param _rateLimitPerSecond the rate limit per second for this rateLimitedAddress
/// @param _bufferCap the buffer cap for this rateLimitedAddress
function _addAddress(
address rateLimitedAddress,
uint112 _rateLimitPerSecond,
uint112 _bufferCap
) internal {
require(
_bufferCap <= bufferCap,
"MultiRateLimited: new buffercap too high"
);
require(
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime == 0,
"MultiRateLimited: address already added"
);
require(
_rateLimitPerSecond <= MAX_RATE_LIMIT_PER_SECOND,
"MultiRateLimited: rateLimitPerSecond too high"
);
RateLimitData memory rateLimitData = RateLimitData({
lastBufferUsedTime: block.timestamp.toUint32(),
bufferCap: _bufferCap,
rateLimitPerSecond: _rateLimitPerSecond,
bufferStored: _bufferCap
});
rateLimitPerAddress[rateLimitedAddress] = rateLimitData;
emit IndividualRateLimitPerSecondUpdate(
rateLimitedAddress,
0,
_rateLimitPerSecond
);
}
/// @notice the method that enforces the rate limit. Decreases buffer by "amount".
/// @param rateLimitedAddress the address whose buffer will be depleted
/// @param amount the amount to remove from the rateLimitedAddress's buffer
function _depleteIndividualBuffer(
address rateLimitedAddress,
uint256 amount
) internal returns (uint256) {
_depleteBuffer(amount);
uint256 newBuffer = individualBuffer(rateLimitedAddress);
require(newBuffer != 0, "MultiRateLimited: no rate limit buffer");
require(amount <= newBuffer, "MultiRateLimited: rate limit hit");
rateLimitPerAddress[rateLimitedAddress].bufferStored = uint112(
newBuffer - amount
);
rateLimitPerAddress[rateLimitedAddress].lastBufferUsedTime = block
.timestamp
.toUint32();
emit IndividualBufferUsed(
rateLimitedAddress,
amount,
newBuffer - amount
);
return amount;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IMultiRateLimited.sol";
/// @notice global contract to handle rate limited minting of VOLT on a global level
/// allows whitelisted minters to call in and specify the address to mint VOLT to within
/// the calling contract's limits
interface IGlobalRateLimitedMinter is IMultiRateLimited {
/// @notice function that all VOLT minters call to mint VOLT
/// pausable and depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// @param amount the amount of VOLT to mint
function mintVolt(address to, uint256 amount) external;
/// @notice mint VOLT to the target address and deplete the whole rate limited
/// minter's buffer, pausable and completely depletes the msg.sender's buffer
/// @param to the recipient address of the minted VOLT
/// mints all VOLT that msg.sender has in the buffer
function mintMaxAllowableVolt(address to) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title interface for putting a rate limit on how fast a contract can perform an action, e.g. Minting
/// @author Fei Protocol
interface IMultiRateLimited {
// ----------- Events -----------
/// @notice emitted when a buffer is eaten into
event IndividualBufferUsed(
address rateLimitedAddress,
uint256 amountUsed,
uint256 bufferRemaining
);
/// @notice emitted when rate limit is updated
event IndividualRateLimitPerSecondUpdate(
address rateLimitedAddress,
uint256 oldRateLimitPerSecond,
uint256 newRateLimitPerSecond
);
/// @notice emitted when the non gov buffer cap max is updated
event MultiBufferCapUpdate(uint256 oldBufferCap, uint256 newBufferCap);
/// @notice emitted when the non gov buffer rate limit per second max is updated
event MultiMaxRateLimitPerSecondUpdate(
uint256 oldMaxRateLimitPerSecond,
uint256 newMaxRateLimitPerSecond
);
// ----------- View API -----------
/// @notice the rate per second for each address
function getRateLimitPerSecond(address) external view returns (uint256);
/// @notice the last time the buffer was used by each address
function getLastBufferUsedTime(address) external view returns (uint256);
/// @notice the cap of the buffer that can be used at once
function getBufferCap(address) external view returns (uint256);
/// @notice the amount of action that can be used before hitting limit
/// @dev replenishes at rateLimitPerSecond per second up to bufferCap
function individualBuffer(address) external view returns (uint112);
// ----------- Governance State Changing API -----------
/// @notice update the non gov max rate limit per second
function updateMaxRateLimitPerSecond(uint256 newMaxRateLimitPerSecond)
external;
/// @notice update the non gov max buffer cap
function updateMaxBufferCap(uint256 newBufferCap) external;
/// @notice add an authorized contract, its per second replenishment and buffer set to the non governor caps
function addAddressWithCaps(address) external;
/// @notice add an authorized contract, its per second replenishment and buffer
function addAddress(
address,
uint112,
uint112
) external;
/// @notice update an authorized contract
function updateAddress(
address,
uint112,
uint112
) external;
/// @notice remove an authorized contract
function removeAddress(address) external;
} | calculate the amount of underlying out for a given `amountVoltIn` of VOLT First get oracle price of token Then figure out how many dollars that amount in is worth by multiplying price amount. ensure decimals are normalized if on underlying they are not 18 amountVoltIn the amount of VOLT to redeem return amountTokenOut the amount of the external asset received in exchange for the amount of VOLT redeemed | function getRedeemAmountOut(uint256 amountVoltIn)
public
view
override
returns (uint256 amountTokenOut)
{
amountTokenOut = _getRedeemAmountOut(amountVoltIn);
}
| 6,870,163 |
pragma solidity 0.4.24;
/* script to setup contracts after full redeploy on Rinkeby.
called via StabilityBoardProxy (MultiSig) but deployer account is the only signer yet because
these working on the new contracts only.
Stability Board and pretoken signers will be added and deployer will be removed when setup is successful.
*/
contract Main0001_initFirstDeploy {
address constant DEPLOYER_ACCOUNT = 0x7b534c2D0F9Ee973e0b6FE8D4000cA711A20f22e;
address constant RATES_FEEDER_ACCOUNT = 0x8C58187a978979947b88824DCdA5Cb5fD4410387;
// new contracts
address constant preTokenProxyAddress = 0x1411b3B189B01f6e6d1eA883bFFcbD3a5224934C;
address constant stabilityBoardProxyAddress = 0x4686f017D456331ed2C1de66e134D8d05B24413D;
PreToken constant preToken = PreToken(0xeCb782B19Be6E657ae2D88831dD98145A00D32D5);
Rates constant rates = Rates(0x4babbe57453e2b6AF125B4e304256fCBDf744480);
FeeAccount constant feeAccount = FeeAccount(0xF6B541E1B5e001DCc11827C1A16232759aeA730a);
AugmintReserves constant augmintReserves = AugmintReserves(0x633cb544b2EF1bd9269B2111fD2B66fC05cd3477);
InterestEarnedAccount constant interestEarnedAccount = InterestEarnedAccount(0x5C1a44E07541203474D92BDD03f803ea74f6947c);
TokenAEur constant tokenAEur = TokenAEur(0x86A635EccEFFfA70Ff8A6DB29DA9C8DB288E40D0);
MonetarySupervisor constant monetarySupervisor = MonetarySupervisor(0x1Ca4F9d261707aF8A856020a4909B777da218868);
LoanManager constant loanManager = LoanManager(0xCBeFaF199b800DEeB9EAd61f358EE46E06c54070);
Locker constant locker = Locker(0x095c0F071Fd75875a6b5a1dEf3f3a993F591080c);
Exchange constant exchange = Exchange(0x8b52b019d237d0bbe8Baedf219132D5254e0690b);
function execute(Main0001_initFirstDeploy /* self, not used */) external {
// called via StabilityBoardProxy
require(address(this) == stabilityBoardProxyAddress, "only deploy via stabilityboardsigner");
/******************************************************************************
* Set up permissions
******************************************************************************/
// preToken Permissions
bytes32[] memory preTokenPermissions = new bytes32[](2); // dynamic array needed for grantMultiplePermissions()
preTokenPermissions[0] = "PreTokenSigner";
preTokenPermissions[1] = "PermissionGranter";
preToken.grantMultiplePermissions(preTokenProxyAddress, preTokenPermissions);
// StabilityBoard
rates.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
feeAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
interestEarnedAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
tokenAEur.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
augmintReserves.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
monetarySupervisor.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
loanManager.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
locker.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
exchange.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
// RatesFeeder permissions to allow calling setRate()
rates.grantPermission(RATES_FEEDER_ACCOUNT, "RatesFeeder");
// set NoTransferFee permissions
feeAccount.grantPermission(feeAccount, "NoTransferFee");
feeAccount.grantPermission(augmintReserves, "NoTransferFee");
feeAccount.grantPermission(interestEarnedAccount, "NoTransferFee");
feeAccount.grantPermission(monetarySupervisor, "NoTransferFee");
feeAccount.grantPermission(loanManager, "NoTransferFee");
feeAccount.grantPermission(locker, "NoTransferFee");
feeAccount.grantPermission(exchange, "NoTransferFee");
// set MonetarySupervisor permissions
interestEarnedAccount.grantPermission(monetarySupervisor, "MonetarySupervisor");
tokenAEur.grantPermission(monetarySupervisor, "MonetarySupervisor");
augmintReserves.grantPermission(monetarySupervisor, "MonetarySupervisor");
// set LoanManager permissions
monetarySupervisor.grantPermission(loanManager, "LoanManager");
// set Locker permissions
monetarySupervisor.grantPermission(locker, "Locker");
/******************************************************************************
* Add loan products
******************************************************************************/
// term (in sec), discountRate, loanCoverageRatio, minDisbursedAmount (w/ 4 decimals), defaultingFeePt, isActive
loanManager.addLoanProduct(30 days, 990641, 600000, 1000, 50000, true); // 12% p.a.
loanManager.addLoanProduct(14 days, 996337, 600000, 1000, 50000, true); // 10% p.a.
loanManager.addLoanProduct(7 days, 998170, 600000, 1000, 50000, true); // 10% p.a.
/******************************************************************************
* Add lock products
******************************************************************************/
// (perTermInterest, durationInSecs, minimumLockAmount, isActive)
locker.addLockProduct(4019, 30 days, 1000, true); // 5% p.a.
locker.addLockProduct(1506, 14 days, 1000, true); // 4% p.a.
locker.addLockProduct(568, 7 days, 1000, true); // 3% p.a.
/******************************************************************************
* Revoke PermissionGranter from deployer account
* NB: migration scripts mistekanly granted it to deployer account (account[0])
* instead of StabilityBoardProxy in constructors
******************************************************************************/
preToken.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
rates.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
feeAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
augmintReserves.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
interestEarnedAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
tokenAEur.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
monetarySupervisor.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
loanManager.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
locker.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
exchange.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
/******************************************************************************
* Revoke PermissionGranter from this contract on preToken
* NB: deploy script temporarly granted PermissionGranter to this script
* now we can remove it as we granted it to preTokenProxy above
******************************************************************************/
preToken.revokePermission(stabilityBoardProxyAddress, "PermissionGranter");
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
TODO: check against ds-math: https://blog.dapphub.com/ds-math/
TODO: move roundedDiv to a sep lib? (eg. Math.sol)
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b, "mul overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason
uint256 c = a / b;
// require(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) {
require(b <= a, "sub underflow");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function roundedDiv(uint a, uint b) internal pure returns (uint256) {
require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason
uint256 z = a / b;
if (a % b >= b / 2) {
z++; // no need for safe add b/c it can happen only if we divided the input
}
return z;
}
}
/*
Generic contract to authorise calls to certain functions only from a given address.
The address authorised must be a contract (multisig or not, depending on the permission), except for local test
deployment works as:
1. contract deployer account deploys contracts
2. constructor grants "PermissionGranter" permission to deployer account
3. deployer account executes initial setup (no multiSig)
4. deployer account grants PermissionGranter permission for the MultiSig contract
(e.g. StabilityBoardProxy or PreTokenProxy)
5. deployer account revokes its own PermissionGranter permission
*/
contract Restricted {
// NB: using bytes32 rather than the string type because it's cheaper gas-wise:
mapping (address => mapping (bytes32 => bool)) public permissions;
event PermissionGranted(address indexed agent, bytes32 grantedPermission);
event PermissionRevoked(address indexed agent, bytes32 revokedPermission);
modifier restrict(bytes32 requiredPermission) {
require(permissions[msg.sender][requiredPermission], "msg.sender must have permission");
_;
}
constructor(address permissionGranterContract) public {
require(permissionGranterContract != address(0), "permissionGranterContract must be set");
permissions[permissionGranterContract]["PermissionGranter"] = true;
emit PermissionGranted(permissionGranterContract, "PermissionGranter");
}
function grantPermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = true;
emit PermissionGranted(agent, requiredPermission);
}
function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
grantPermission(agent, requiredPermissions[i]);
}
}
function revokePermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = false;
emit PermissionRevoked(agent, requiredPermission);
}
function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
revokePermission(agent, requiredPermissions[i]);
}
}
}
/* Abstract multisig contract to allow multi approval execution of atomic contracts scripts
e.g. migrations or settings.
* Script added by signing a script address by a signer (NEW state)
* Script goes to ALLOWED state once a quorom of signers sign it (quorom fx is defined in each derived contracts)
* Script can be signed even in APPROVED state
* APPROVED scripts can be executed only once.
- if script succeeds then state set to DONE
- If script runs out of gas or reverts then script state set to FAILEd and not allowed to run again
(To avoid leaving "behind" scripts which fail in a given state but eventually execute in the future)
* Scripts can be cancelled by an other multisig script approved and calling cancelScript()
* Adding/removing signers is only via multisig approved scripts using addSigners / removeSigners fxs
*/
contract MultiSig {
using SafeMath for uint256;
uint public constant CHUNK_SIZE = 100;
mapping(address => bool) public isSigner;
address[] public allSigners; // all signers, even the disabled ones
// NB: it can contain duplicates when a signer is added, removed then readded again
// the purpose of this array is to being able to iterate on signers in isSigner
uint public activeSignersCount;
enum ScriptState {New, Approved, Done, Cancelled, Failed}
struct Script {
ScriptState state;
uint signCount;
mapping(address => bool) signedBy;
address[] allSigners;
}
mapping(address => Script) public scripts;
address[] public scriptAddresses;
event SignerAdded(address signer);
event SignerRemoved(address signer);
event ScriptSigned(address scriptAddress, address signer);
event ScriptApproved(address scriptAddress);
event ScriptCancelled(address scriptAddress);
event ScriptExecuted(address scriptAddress, bool result);
constructor() public {
// deployer address is the first signer. Deployer can configure new contracts by itself being the only "signer"
// The first script which sets the new contracts live should add signers and revoke deployer's signature right
isSigner[msg.sender] = true;
allSigners.push(msg.sender);
activeSignersCount = 1;
emit SignerAdded(msg.sender);
}
function sign(address scriptAddress) public {
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved || script.state == ScriptState.New,
"script state must be New or Approved");
require(!script.signedBy[msg.sender], "script must not be signed by signer yet");
if(script.allSigners.length == 0) {
// first sign of a new script
scriptAddresses.push(scriptAddress);
}
script.allSigners.push(msg.sender);
script.signedBy[msg.sender] = true;
script.signCount = script.signCount.add(1);
emit ScriptSigned(scriptAddress, msg.sender);
if(checkQuorum(script.signCount)){
script.state = ScriptState.Approved;
emit ScriptApproved(scriptAddress);
}
}
function execute(address scriptAddress) public returns (bool result) {
// only allow execute to signers to avoid someone set an approved script failed by calling it with low gaslimit
require(isSigner[msg.sender], "sender must be signer");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved, "script state must be Approved");
/* init to failed because if delegatecall rans out of gas we won't have enough left to set it.
NB: delegatecall leaves 63/64 part of gasLimit for the caller.
Therefore the execute might revert with out of gas, leaving script in Approved state
when execute() is called with small gas limits.
*/
script.state = ScriptState.Failed;
// passing scriptAddress to allow called script access its own public fx-s if needed
if(scriptAddress.delegatecall(bytes4(keccak256("execute(address)")), scriptAddress)) {
script.state = ScriptState.Done;
result = true;
} else {
result = false;
}
emit ScriptExecuted(scriptAddress, result);
}
function cancelScript(address scriptAddress) public {
require(msg.sender == address(this), "only callable via MultiSig");
Script storage script = scripts[scriptAddress];
require(script.state == ScriptState.Approved || script.state == ScriptState.New,
"script state must be New or Approved");
script.state= ScriptState.Cancelled;
emit ScriptCancelled(scriptAddress);
}
/* requires quorum so it's callable only via a script executed by this contract */
function addSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (!isSigner[signers[i]]) {
require(signers[i] != address(0), "new signer must not be 0x0");
activeSignersCount++;
allSigners.push(signers[i]);
isSigner[signers[i]] = true;
emit SignerAdded(signers[i]);
}
}
}
/* requires quorum so it's callable only via a script executed by this contract */
function removeSigners(address[] signers) public {
require(msg.sender == address(this), "only callable via MultiSig");
for (uint i= 0; i < signers.length; i++) {
if (isSigner[signers[i]]) {
require(activeSignersCount > 1, "must not remove last signer");
activeSignersCount--;
isSigner[signers[i]] = false;
emit SignerRemoved(signers[i]);
}
}
}
/* implement it in derived contract */
function checkQuorum(uint signersCount) internal view returns(bool isQuorum);
function getAllSignersCount() view external returns (uint allSignersCount) {
return allSigners.length;
}
// UI helper fx - Returns signers from offset as [signer id (index in allSigners), address as uint, isActive 0 or 1]
function getAllSigners(uint offset) external view returns(uint[3][CHUNK_SIZE] signersResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allSigners.length; i++) {
address signerAddress = allSigners[i + offset];
signersResult[i] = [ i + offset, uint(signerAddress), isSigner[signerAddress] ? 1 : 0 ];
}
}
function getScriptsCount() view external returns (uint scriptsCount) {
return scriptAddresses.length;
}
// UI helper fx - Returns scripts from offset as
// [scriptId (index in scriptAddresses[]), address as uint, state, signCount]
function getAllScripts(uint offset) external view returns(uint[4][CHUNK_SIZE] scriptsResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < scriptAddresses.length; i++) {
address scriptAddress = scriptAddresses[i + offset];
scriptsResult[i] = [ i + offset, uint(scriptAddress), uint(scripts[scriptAddress].state),
scripts[scriptAddress].signCount ];
}
}
}
/* Augmint pretoken contract to record agreements and tokens allocated based on the agreement.
Important: this is NOT an ERC20 token!
PreTokens are non-fungible: agreements can have different conditions (valuationCap and discount)
and pretokens are not tradable.
Ownership can be transferred if owner wants to change wallet but the whole agreement and
the total pretoken amount is moved to a new account
PreTokenSigner can (via MultiSig):
- add agreements and issue pretokens to an agreement
- change owner of any agreement to handle if an owner lost a private keys
- burn pretokens from any agreement to fix potential erroneous issuance
These are known compromises on trustlessness hence all these tokens distributed based on signed agreements and
preTokens are issued only to a closed group of contributors / team members.
If despite these something goes wrong then as a last resort a new pretoken contract can be recreated from agreements.
Some ERC20 functions are implemented so agreement owners can see their balances and use transfer in standard wallets.
Restrictions:
- only total balance can be transfered - effectively ERC20 transfer used to transfer agreement ownership
- only agreement holders can transfer
(i.e. can't transfer 0 amount if have no agreement to avoid polluting logs with Transfer events)
- transfer is only allowed to accounts without an agreement yet
- no approval and transferFrom ERC20 functions
*/
contract PreToken is Restricted {
using SafeMath for uint256;
uint public constant CHUNK_SIZE = 100;
string constant public name = "Augmint pretokens"; // solhint-disable-line const-name-snakecase
string constant public symbol = "APRE"; // solhint-disable-line const-name-snakecase
uint8 constant public decimals = 0; // solhint-disable-line const-name-snakecase
uint public totalSupply;
struct Agreement {
address owner;
uint balance;
uint32 discount; // discountRate in parts per million , ie. 10,000 = 1%
uint32 valuationCap; // in USD (no decimals)
}
/* Agreement hash is the SHA-2 (SHA-256) hash of signed agreement document.
To generate:
OSX: shasum -a 256 agreement.pdf
Windows: certUtil -hashfile agreement.pdf SHA256 */
mapping(address => bytes32) public agreementOwners; // to lookup agrement by owner
mapping(bytes32 => Agreement) public agreements;
bytes32[] public allAgreements; // all agreements to able to iterate over
event Transfer(address indexed from, address indexed to, uint amount);
event NewAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap);
constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks
function addAgreement(address owner, bytes32 agreementHash, uint32 discount, uint32 valuationCap)
external restrict("PreTokenSigner") {
require(owner != address(0), "owner must not be 0x0");
require(agreementOwners[owner] == 0x0, "owner must not have an aggrement yet");
require(agreementHash != 0x0, "agreementHash must not be 0x0");
require(discount > 0, "discount must be > 0");
require(agreements[agreementHash].discount == 0, "agreement must not exist yet");
agreements[agreementHash] = Agreement(owner, 0, discount, valuationCap);
agreementOwners[owner] = agreementHash;
allAgreements.push(agreementHash);
emit NewAgreement(owner, agreementHash, discount, valuationCap);
}
function issueTo(bytes32 agreementHash, uint amount) external restrict("PreTokenSigner") {
Agreement storage agreement = agreements[agreementHash];
require(agreement.discount > 0, "agreement must exist");
agreement.balance = agreement.balance.add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, agreement.owner, amount);
}
/* Restricted function to allow pretoken signers to fix incorrect issuance */
function burnFrom(bytes32 agreementHash, uint amount)
public restrict("PreTokenSigner") returns (bool) {
Agreement storage agreement = agreements[agreementHash];
require(agreement.discount > 0, "agreement must exist"); // this is redundant b/c of next requires but be explicit
require(amount > 0, "burn amount must be > 0");
require(agreement.balance >= amount, "must not burn more than balance"); // .sub would revert anyways but emit reason
agreement.balance = agreement.balance.sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(agreement.owner, 0x0, amount);
return true;
}
function balanceOf(address owner) public view returns (uint) {
return agreements[agreementOwners[owner]].balance;
}
/* function to transfer agreement ownership to other wallet by owner
it's in ERC20 form so owners can use standard ERC20 wallet just need to pass full balance as value */
function transfer(address to, uint amount) public returns (bool) { // solhint-disable-line no-simple-event-func-name
require(amount == agreements[agreementOwners[msg.sender]].balance, "must transfer full balance");
_transfer(msg.sender, to);
return true;
}
/* Restricted function to allow pretoken signers to fix if pretoken owner lost keys */
function transferAgreement(bytes32 agreementHash, address to)
public restrict("PreTokenSigner") returns (bool) {
_transfer(agreements[agreementHash].owner, to);
return true;
}
/* private function used by transferAgreement & transfer */
function _transfer(address from, address to) private {
Agreement storage agreement = agreements[agreementOwners[from]];
require(agreementOwners[from] != 0x0, "from agreement must exists");
require(agreementOwners[to] == 0, "to must not have an agreement");
require(to != 0x0, "must not transfer to 0x0");
agreement.owner = to;
agreementOwners[to] = agreementOwners[from];
agreementOwners[from] = 0x0;
emit Transfer(from, to, agreement.balance);
}
function getAgreementsCount() external view returns (uint agreementsCount) {
return allAgreements.length;
}
// UI helper fx - Returns all agreements from offset as
// [index in allAgreements, account address as uint, balance, agreementHash as uint,
// discount as uint, valuationCap as uint ]
function getAllAgreements(uint offset) external view returns(uint[6][CHUNK_SIZE] agreementsResult) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < allAgreements.length; i++) {
bytes32 agreementHash = allAgreements[i + offset];
Agreement storage agreement = agreements[agreementHash];
agreementsResult[i] = [ i + offset, uint(agreement.owner), agreement.balance,
uint(agreementHash), uint(agreement.discount), uint(agreement.valuationCap)];
}
}
}
/*
Generic symbol / WEI rates contract.
only callable by trusted price oracles.
Being regularly called by a price oracle
TODO: trustless/decentrilezed price Oracle
TODO: shall we use blockNumber instead of now for lastUpdated?
TODO: consider if we need storing rates with variable decimals instead of fixed 4
TODO: could we emit 1 RateChanged event from setMultipleRates (symbols and newrates arrays)?
*/
contract Rates is Restricted {
using SafeMath for uint256;
struct RateInfo {
uint rate; // how much 1 WEI worth 1 unit , i.e. symbol/ETH rate
// 0 rate means no rate info available
uint lastUpdated;
}
// mapping currency symbol => rate. all rates are stored with 4 decimals. i.e. ETH/EUR = 989.12 then rate = 989,1200
mapping(bytes32 => RateInfo) public rates;
event RateChanged(bytes32 symbol, uint newRate);
constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks
function setRate(bytes32 symbol, uint newRate) external restrict("RatesFeeder") {
rates[symbol] = RateInfo(newRate, now);
emit RateChanged(symbol, newRate);
}
function setMultipleRates(bytes32[] symbols, uint[] newRates) external restrict("RatesFeeder") {
require(symbols.length == newRates.length, "symobls and newRates lengths must be equal");
for (uint256 i = 0; i < symbols.length; i++) {
rates[symbols[i]] = RateInfo(newRates[i], now);
emit RateChanged(symbols[i], newRates[i]);
}
}
function convertFromWei(bytes32 bSymbol, uint weiValue) external view returns(uint value) {
require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0");
return weiValue.mul(rates[bSymbol].rate).roundedDiv(1000000000000000000);
}
function convertToWei(bytes32 bSymbol, uint value) external view returns(uint weiValue) {
// next line would revert with div by zero but require to emit reason
require(rates[bSymbol].rate > 0, "rates[bSymbol] must be > 0");
/* TODO: can we make this not loosing max scale? */
return value.mul(1000000000000000000).roundedDiv(rates[bSymbol].rate);
}
}
contract SystemAccount is Restricted {
event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount,
string narrative);
constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks
/* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs.
remove this function for higher volume pilots */
function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative)
external restrict("StabilityBoard") {
tokenAddress.transferWithNarrative(to, tokenAmount, narrative);
if (weiAmount > 0) {
to.transfer(weiAmount);
}
emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative);
}
}
interface TokenReceiver {
function transferNotification(address from, uint256 amount, uint data) external;
}
interface TransferFeeInterface {
function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee);
}
interface ExchangeFeeInterface {
function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee);
}
interface ERC20Interface {
event Approval(address indexed _owner, address indexed _spender, uint _value);
event Transfer(address indexed from, address indexed to, uint amount);
function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function balanceOf(address who) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint remaining);
}
/* Augmint Token interface (abstract contract)
TODO: overload transfer() & transferFrom() instead of transferWithNarrative() & transferFromWithNarrative()
when this fix available in web3& truffle also uses that web3: https://github.com/ethereum/web3.js/pull/1185
TODO: shall we use bytes for narrative?
*/
contract AugmintTokenInterface is Restricted, ERC20Interface {
using SafeMath for uint256;
string public name;
string public symbol;
bytes32 public peggedSymbol;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint256) public balances; // Balances for each account
mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve()
address public stabilityBoardProxy;
TransferFeeInterface public feeAccount;
mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer
event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax);
event Transfer(address indexed from, address indexed to, uint amount);
event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee);
event TokenIssued(uint amount);
event TokenBurned(uint amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
) external;
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
) external;
function increaseApproval(address spender, uint addedValue) external returns (bool);
function decreaseApproval(address spender, uint subtractedValue) external returns (bool);
function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.;
function burn(uint amount) external;
function transferAndNotify(TokenReceiver target, uint amount, uint data) external;
function transferWithNarrative(address to, uint256 amount, string narrative) external;
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external;
function allowance(address owner, address spender) external view returns (uint256 remaining);
function balanceOf(address who) external view returns (uint);
}
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol
*
* 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(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/* Generic Augmint Token implementation (ERC20 token)
This contract manages:
* Balances of Augmint holders and transactions between them
* Issues/burns tokens
TODO:
- reconsider delegatedTransfer and how to structure it
- shall we allow change of txDelegator?
- consider generic bytes arg instead of uint for transferAndNotify
- consider separate transfer fee params and calculation to separate contract (to feeAccount?)
*/
contract AugmintToken is AugmintTokenInterface {
event FeeAccountChanged(TransferFeeInterface newFeeAccount);
constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount)
public Restricted(permissionGranterContract) {
require(_feeAccount != address(0), "feeAccount must be set");
require(bytes(_name).length > 0, "name must be set");
require(bytes(_symbol).length > 0, "symbol must be set");
name = _name;
symbol = _symbol;
peggedSymbol = _peggedSymbol;
decimals = _decimals;
feeAccount = _feeAccount;
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount, "");
return true;
}
/* Transfers based on an offline signed transfer instruction. */
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, to, amount, narrative);
}
function approve(address _spender, uint256 amount) external returns (bool) {
require(_spender != 0x0, "spender must be set");
allowed[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/**
ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57
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)
Based on MonolithDAO Token.sol */
function increaseApproval(address _spender, uint _addedValue) external returns (bool) {
return _increaseApproval(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) external 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;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
_transferFrom(from, to, amount, "");
return true;
}
// Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed:
// - on new loan (by trusted Lender contracts)
// - when converting old tokens using MonetarySupervisor
// - strictly to reserve by Stability Board (via MonetarySupervisor)
function issueTo(address to, uint amount) external restrict("MonetarySupervisor") {
balances[to] = balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, to, amount);
emit AugmintTransfer(0x0, to, amount, "", 0);
}
// Burn tokens. Anyone can burn from its own account. YOLO.
// Used by to burn from Augmint reserve or by Lender contract after loan repayment
function burn(uint amount) external {
require(balances[msg.sender] >= amount, "balance must be >= amount");
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(msg.sender, 0x0, amount);
emit AugmintTransfer(msg.sender, 0x0, amount, "", 0);
}
/* to upgrade feeAccount (eg. for fee calculation changes) */
function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") {
feeAccount = newFeeAccount;
emit FeeAccountChanged(newFeeAccount);
}
/* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call)
Eg. repay loan, lock funds, token sell order on exchange
Reverts on failue:
- transfer fails
- if transferNotification fails (callee must revert on failure)
- if targetContract is an account or targetContract doesn't have neither transferNotification or fallback fx
TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification)
*/
function transferAndNotify(TokenReceiver target, uint amount, uint data) external {
_transfer(msg.sender, target, amount, "");
target.transferNotification(msg.sender, amount, data);
}
/* transferAndNotify based on an instruction signed offline */
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, target, amount, "");
target.transferNotification(from, amount, data);
}
function transferWithNarrative(address to, uint256 amount, string narrative) external {
_transfer(msg.sender, to, amount, narrative);
}
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external {
_transferFrom(from, to, amount, narrative);
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer,
uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private {
require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee");
require(!delegatedTxHashesUsed[txHash], "txHash already used");
delegatedTxHashesUsed[txHash] = true;
address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature);
require(recovered == signer, "invalid signature");
_transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0);
}
function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) {
allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue);
emit Approval(_approver, _spender, allowed[_approver][_spender]);
}
function _transferFrom(address from, address to, uint256 amount, string narrative) private {
require(balances[from] >= amount, "balance must >= amount");
require(allowed[from][msg.sender] >= amount, "allowance must be >= amount");
// don't allow 0 transferFrom if no approval:
require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount");
/* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail
when x + fee is not availale on owner balance */
_transfer(from, to, amount, narrative);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
}
function _transfer(address from, address to, uint transferAmount, string narrative) private {
uint fee = feeAccount.calculateTransferFee(from, to, transferAmount);
_transfer(from, to, transferAmount, narrative, fee);
}
function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private {
require(to != 0x0, "to must be set");
uint amountWithFee = transferAmount.add(fee);
// to emit proper reason instead of failing on from.sub()
require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee");
if (fee > 0) {
balances[feeAccount] = balances[feeAccount].add(fee);
emit Transfer(from, feeAccount, fee);
}
balances[from] = balances[from].sub(amountWithFee);
balances[to] = balances[to].add(transferAmount);
emit Transfer(from, to, transferAmount);
emit AugmintTransfer(from, to, transferAmount, narrative, fee);
}
}
/* Contract to collect fees from system
TODO: calculateExchangeFee + Exchange params and setters
*/
contract FeeAccount is SystemAccount, TransferFeeInterface {
using SafeMath for uint256;
struct TransferFee {
uint pt; // in parts per million (ppm) , ie. 2,000 = 0.2%
uint min; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE
uint max; // with base unit of augmint token, eg. 2 decimals for token, eg. 310 = 3.1 ACE
}
TransferFee public transferFee;
event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax);
constructor(address permissionGranterContract, uint transferFeePt, uint transferFeeMin, uint transferFeeMax)
public SystemAccount(permissionGranterContract) {
transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax);
}
function () public payable { // solhint-disable-line no-empty-blocks
// to accept ETH sent into feeAccount (defaulting fee in ETH )
}
function setTransferFees(uint transferFeePt, uint transferFeeMin, uint transferFeeMax)
external restrict("StabilityBoard") {
transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax);
emit TransferFeesChanged(transferFeePt, transferFeeMin, transferFeeMax);
}
function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee) {
if (!permissions[from]["NoTransferFee"] && !permissions[to]["NoTransferFee"]) {
fee = amount.mul(transferFee.pt).div(1000000);
if (fee > transferFee.max) {
fee = transferFee.max;
} else if (fee < transferFee.min) {
fee = transferFee.min;
}
}
return fee;
}
function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee) {
/* TODO: to be implemented and use in Exchange.sol. always revert for now */
require(weiAmount != weiAmount, "not yet implemented");
weiFee = transferFee.max; // to silence compiler warnings until it's implemented
}
}
/* Contract to hold earned interest from loans repaid
premiums for locks are being accrued (i.e. transferred) to Locker */
contract InterestEarnedAccount is SystemAccount {
constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks
function transferInterest(AugmintTokenInterface augmintToken, address locker, uint interestAmount)
external restrict("MonetarySupervisor") {
augmintToken.transfer(locker, interestAmount);
}
}
/* Contract to hold Augmint reserves (ETH & Token)
- ETH as regular ETH balance of the contract
- ERC20 token reserve (stored as regular Token balance under the contract address)
NB: reserves are held under the contract address, therefore any transaction on the reserve is limited to the
tx-s defined here (i.e. transfer is not allowed even by the contract owner or StabilityBoard or MonetarySupervisor)
*/
contract AugmintReserves is SystemAccount {
function () public payable { // solhint-disable-line no-empty-blocks
// to accept ETH sent into reserve (from defaulted loan's collateral )
}
constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks
function burn(AugmintTokenInterface augmintToken, uint amount) external restrict("MonetarySupervisor") {
augmintToken.burn(amount);
}
}
/* MonetarySupervisor
- maintains system wide KPIs (eg totalLockAmount, totalLoanAmount)
- holds system wide parameters/limits
- enforces system wide limits
- burns and issues to AugmintReserves
- Send funds from reserve to exchange when intervening (not implemented yet)
- Converts older versions of AugmintTokens in 1:1 to new
*/
contract MonetarySupervisor is Restricted, TokenReceiver { // solhint-disable-line no-empty-blocks
using SafeMath for uint256;
uint public constant PERCENT_100 = 1000000;
AugmintTokenInterface public augmintToken;
InterestEarnedAccount public interestEarnedAccount;
AugmintReserves public augmintReserves;
uint public issuedByStabilityBoard; // token issued by Stability Board
uint public totalLoanAmount; // total amount of all loans without interest, in token
uint public totalLockedAmount; // total amount of all locks without premium, in token
/**********
Parameters to ensure totalLoanAmount or totalLockedAmount difference is within limits and system also works
when total loan or lock amounts are low.
for test calculations: https://docs.google.com/spreadsheets/d/1MeWYPYZRIm1n9lzpvbq8kLfQg1hhvk5oJY6NrR401S0
**********/
struct LtdParams {
uint lockDifferenceLimit; /* only allow a new lock if Loan To Deposit ratio would stay above
(1 - lockDifferenceLimit) with new lock. Stored as parts per million */
uint loanDifferenceLimit; /* only allow a new loan if Loan To Deposit ratio would stay above
(1 + loanDifferenceLimit) with new loan. Stored as parts per million */
/* allowedDifferenceAmount param is to ensure the system is not "freezing" when totalLoanAmount or
totalLockAmount is low.
It allows a new loan or lock (up to an amount to reach this difference) even if LTD will go below / above
lockDifferenceLimit / loanDifferenceLimit with the new lock/loan */
uint allowedDifferenceAmount;
}
LtdParams public ltdParams;
/* Previously deployed AugmintTokens which are accepted for conversion (see transferNotification() )
NB: it's not iterable so old version addresses needs to be added for UI manually after each deploy */
mapping(address => bool) public acceptedLegacyAugmintTokens;
event LtdParamsChanged(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount);
event AcceptedLegacyAugmintTokenChanged(address augmintTokenAddress, bool newAcceptedState);
event LegacyTokenConverted(address oldTokenAddress, address account, uint amount);
event KPIsAdjusted(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment);
event SystemContractsChanged(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves);
constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, AugmintReserves _augmintReserves,
InterestEarnedAccount _interestEarnedAccount,
uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount)
public Restricted(permissionGranterContract) {
augmintToken = _augmintToken;
augmintReserves = _augmintReserves;
interestEarnedAccount = _interestEarnedAccount;
ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount);
}
function issueToReserve(uint amount) external restrict("StabilityBoard") {
issuedByStabilityBoard = issuedByStabilityBoard.add(amount);
augmintToken.issueTo(augmintReserves, amount);
}
function burnFromReserve(uint amount) external restrict("StabilityBoard") {
issuedByStabilityBoard = issuedByStabilityBoard.sub(amount);
augmintReserves.burn(augmintToken, amount);
}
/* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params
NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */
function requestInterest(uint amountToLock, uint interestAmount) external {
// only whitelisted Locker
require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission");
require(amountToLock <= getMaxLockAmountAllowedByLtd(), "amountToLock must be <= maxLockAmountAllowedByLtd");
totalLockedAmount = totalLockedAmount.add(amountToLock);
// next line would revert but require to emit reason:
require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount,
"interestEarnedAccount balance must be >= interestAmount");
interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker
}
// Locker notifying when releasing funds to update KPIs
function releaseFundsNotification(uint lockedAmount) external {
// only whitelisted Locker
require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission");
totalLockedAmount = totalLockedAmount.sub(lockedAmount);
}
/* Issue loan if LTD stays within range allowed by LTD params
NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */
function issueLoan(address borrower, uint loanAmount) external {
// only whitelisted LoanManager contracts
require(permissions[msg.sender]["LoanManager"],
"msg.sender must have LoanManager permission");
require(loanAmount <= getMaxLoanAmountAllowedByLtd(), "loanAmount must be <= maxLoanAmountAllowedByLtd");
totalLoanAmount = totalLoanAmount.add(loanAmount);
augmintToken.issueTo(borrower, loanAmount);
}
function loanRepaymentNotification(uint loanAmount) external {
// only whitelisted LoanManager contracts
require(permissions[msg.sender]["LoanManager"],
"msg.sender must have LoanManager permission");
totalLoanAmount = totalLoanAmount.sub(loanAmount);
}
// NB: this is called by Lender contract with the sum of all loans collected in batch
function loanCollectionNotification(uint totalLoanAmountCollected) external {
// only whitelisted LoanManager contracts
require(permissions[msg.sender]["LoanManager"],
"msg.sender must have LoanManager permission");
totalLoanAmount = totalLoanAmount.sub(totalLoanAmountCollected);
}
function setAcceptedLegacyAugmintToken(address legacyAugmintTokenAddress, bool newAcceptedState)
external restrict("StabilityBoard") {
acceptedLegacyAugmintTokens[legacyAugmintTokenAddress] = newAcceptedState;
emit AcceptedLegacyAugmintTokenChanged(legacyAugmintTokenAddress, newAcceptedState);
}
function setLtdParams(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount)
external restrict("StabilityBoard") {
ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount);
emit LtdParamsChanged(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount);
}
/* function to migrate old totalLoanAmount and totalLockedAmount from old monetarySupervisor contract
when it's upgraded.
Set new monetarySupervisor contract in all locker and loanManager contracts before executing this */
function adjustKPIs(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment)
external restrict("StabilityBoard") {
totalLoanAmount = totalLoanAmount.add(totalLoanAmountAdjustment);
totalLockedAmount = totalLockedAmount.add(totalLockedAmountAdjustment);
emit KPIsAdjusted(totalLoanAmountAdjustment, totalLockedAmountAdjustment);
}
/* to allow upgrades of InterestEarnedAccount and AugmintReserves contracts. */
function setSystemContracts(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves)
external restrict("StabilityBoard") {
interestEarnedAccount = newInterestEarnedAccount;
augmintReserves = newAugmintReserves;
emit SystemContractsChanged(newInterestEarnedAccount, newAugmintReserves);
}
/* User can request to convert their tokens from older AugmintToken versions in 1:1
transferNotification is called from AugmintToken's transferAndNotify
Flow for converting old tokens:
1) user calls old token contract's transferAndNotify with the amount to convert,
addressing the new MonetarySupervisor Contract
2) transferAndNotify transfers user's old tokens to the current MonetarySupervisor contract's address
3) transferAndNotify calls MonetarySupervisor.transferNotification
4) MonetarySupervisor checks if old AugmintToken is permitted
5) MonetarySupervisor issues new tokens to user's account in current AugmintToken
6) MonetarySupervisor burns old tokens from own balance
*/
function transferNotification(address from, uint amount, uint /* data, not used */ ) external {
AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender);
require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens");
legacyToken.burn(amount);
augmintToken.issueTo(from, amount);
emit LegacyTokenConverted(msg.sender, from, amount);
}
function getLoanToDepositRatio() external view returns (uint loanToDepositRatio) {
loanToDepositRatio = totalLockedAmount == 0 ? 0 : totalLockedAmount.mul(PERCENT_100).div(totalLoanAmount);
}
/* Helper function for UI.
Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */
function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) {
uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt);
uint allowedByLtd = getMaxLockAmountAllowedByLtd();
maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd;
maxLock = maxLock < minLockAmount ? 0 : maxLock;
}
/* Helper function for UI.
Returns max loan amount based on minLoanAmont using LTD params */
function getMaxLoanAmount(uint minLoanAmount) external view returns (uint maxLoan) {
uint allowedByLtd = getMaxLoanAmountAllowedByLtd();
maxLoan = allowedByLtd < minLoanAmount ? 0 : allowedByLtd;
}
/* returns maximum lockable token amount allowed by LTD params. */
function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) {
uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100
.sub(ltdParams.lockDifferenceLimit));
allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ?
0 : allowedByLtdDifferencePt.sub(totalLockedAmount);
uint allowedByLtdDifferenceAmount =
totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ?
0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount);
maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ?
allowedByLtdDifferencePt : allowedByLtdDifferenceAmount;
}
/* returns maximum borrowable token amount allowed by LTD params */
function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) {
uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100))
.div(PERCENT_100);
allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ?
0 : allowedByLtdDifferencePt.sub(totalLoanAmount);
uint allowedByLtdDifferenceAmount =
totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ?
0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount);
maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ?
allowedByLtdDifferencePt : allowedByLtdDifferenceAmount;
}
}
/* Augmint's Internal Exchange
For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/exchangeFlow.png
TODO:
- change to wihtdrawal pattern, see: https://github.com/Augmint/augmint-contracts/issues/17
- deduct fee
- consider take funcs (frequent rate changes with takeBuyToken? send more and send back remainder?)
- use Rates interface?
*/
pragma solidity 0.4.24;
contract Exchange is Restricted {
using SafeMath for uint256;
AugmintTokenInterface public augmintToken;
Rates public rates;
uint public constant CHUNK_SIZE = 100;
struct Order {
uint64 index;
address maker;
// % of published current peggedSymbol/ETH rates published by Rates contract. Stored as parts per million
// I.e. 1,000,000 = 100% (parity), 990,000 = 1% below parity
uint32 price;
// buy order: amount in wei
// sell order: token amount
uint amount;
}
uint64 public orderCount;
mapping(uint64 => Order) public buyTokenOrders;
mapping(uint64 => Order) public sellTokenOrders;
uint64[] private activeBuyOrders;
uint64[] private activeSellOrders;
/* used to stop executing matchMultiple when running out of gas.
actual is much less, just leaving enough matchMultipleOrders() to finish TODO: fine tune & test it*/
uint32 private constant ORDER_MATCH_WORST_GAS = 100000;
event NewOrder(uint64 indexed orderId, address indexed maker, uint32 price, uint tokenAmount, uint weiAmount);
event OrderFill(address indexed tokenBuyer, address indexed tokenSeller, uint64 buyTokenOrderId,
uint64 sellTokenOrderId, uint publishedRate, uint32 price, uint fillRate, uint weiAmount, uint tokenAmount);
event CancelledOrder(uint64 indexed orderId, address indexed maker, uint tokenAmount, uint weiAmount);
event RatesContractChanged(Rates newRatesContract);
constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, Rates _rates)
public Restricted(permissionGranterContract) {
augmintToken = _augmintToken;
rates = _rates;
}
/* to allow upgrade of Rates contract */
function setRatesContract(Rates newRatesContract)
external restrict("StabilityBoard") {
rates = newRatesContract;
emit RatesContractChanged(newRatesContract);
}
function placeBuyTokenOrder(uint32 price) external payable returns (uint64 orderId) {
require(price > 0, "price must be > 0");
require(msg.value > 0, "msg.value must be > 0");
orderId = ++orderCount;
buyTokenOrders[orderId] = Order(uint64(activeBuyOrders.length), msg.sender, price, msg.value);
activeBuyOrders.push(orderId);
emit NewOrder(orderId, msg.sender, price, 0, msg.value);
}
/* this function requires previous approval to transfer tokens */
function placeSellTokenOrder(uint32 price, uint tokenAmount) external returns (uint orderId) {
augmintToken.transferFrom(msg.sender, this, tokenAmount);
return _placeSellTokenOrder(msg.sender, price, tokenAmount);
}
/* place sell token order called from AugmintToken's transferAndNotify
Flow:
1) user calls token contract's transferAndNotify price passed in data arg
2) transferAndNotify transfers tokens to the Exchange contract
3) transferAndNotify calls Exchange.transferNotification with lockProductId
*/
function transferNotification(address maker, uint tokenAmount, uint price) external {
require(msg.sender == address(augmintToken), "msg.sender must be augmintToken");
_placeSellTokenOrder(maker, uint32(price), tokenAmount);
}
function cancelBuyTokenOrder(uint64 buyTokenId) external {
Order storage order = buyTokenOrders[buyTokenId];
require(order.maker == msg.sender, "msg.sender must be order.maker");
require(order.amount > 0, "buy order already removed");
uint amount = order.amount;
order.amount = 0;
_removeBuyOrder(order);
msg.sender.transfer(amount);
emit CancelledOrder(buyTokenId, msg.sender, 0, amount);
}
function cancelSellTokenOrder(uint64 sellTokenId) external {
Order storage order = sellTokenOrders[sellTokenId];
require(order.maker == msg.sender, "msg.sender must be order.maker");
require(order.amount > 0, "sell order already removed");
uint amount = order.amount;
order.amount = 0;
_removeSellOrder(order);
augmintToken.transferWithNarrative(msg.sender, amount, "Sell token order cancelled");
emit CancelledOrder(sellTokenId, msg.sender, amount, 0);
}
/* matches any two orders if the sell price >= buy price
trade price is the price of the maker (the order placed earlier)
reverts if any of the orders have been removed
*/
function matchOrders(uint64 buyTokenId, uint64 sellTokenId) external {
require(_fillOrder(buyTokenId, sellTokenId), "fill order failed");
}
/* matches as many orders as possible from the passed orders
Runs as long as gas is available for the call.
Reverts if any match is invalid (e.g sell price > buy price)
Skips match if any of the matched orders is removed / already filled (i.e. amount = 0)
*/
function matchMultipleOrders(uint64[] buyTokenIds, uint64[] sellTokenIds) external returns(uint matchCount) {
uint len = buyTokenIds.length;
require(len == sellTokenIds.length, "buyTokenIds and sellTokenIds lengths must be equal");
for (uint i = 0; i < len && gasleft() > ORDER_MATCH_WORST_GAS; i++) {
if(_fillOrder(buyTokenIds[i], sellTokenIds[i])) {
matchCount++;
}
}
}
function getActiveOrderCounts() external view returns(uint buyTokenOrderCount, uint sellTokenOrderCount) {
return(activeBuyOrders.length, activeSellOrders.length);
}
// returns CHUNK_SIZE orders starting from offset
// orders are encoded as [id, maker, price, amount]
function getActiveBuyOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeBuyOrders.length; i++) {
uint64 orderId = activeBuyOrders[offset + i];
Order storage order = buyTokenOrders[orderId];
response[i] = [orderId, uint(order.maker), order.price, order.amount];
}
}
function getActiveSellOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeSellOrders.length; i++) {
uint64 orderId = activeSellOrders[offset + i];
Order storage order = sellTokenOrders[orderId];
response[i] = [orderId, uint(order.maker), order.price, order.amount];
}
}
function _fillOrder(uint64 buyTokenId, uint64 sellTokenId) private returns(bool success) {
Order storage buy = buyTokenOrders[buyTokenId];
Order storage sell = sellTokenOrders[sellTokenId];
if( buy.amount == 0 || sell.amount == 0 ) {
return false; // one order is already filled and removed.
// we let matchMultiple continue, indivudal match will revert
}
require(buy.price >= sell.price, "buy price must be >= sell price");
// pick maker's price (whoever placed order sooner considered as maker)
uint32 price = buyTokenId > sellTokenId ? sell.price : buy.price;
uint publishedRate;
(publishedRate, ) = rates.rates(augmintToken.peggedSymbol());
uint fillRate = publishedRate.mul(price).roundedDiv(1000000);
uint sellWei = sell.amount.mul(1 ether).roundedDiv(fillRate);
uint tradedWei;
uint tradedTokens;
if (sellWei <= buy.amount) {
tradedWei = sellWei;
tradedTokens = sell.amount;
} else {
tradedWei = buy.amount;
tradedTokens = buy.amount.mul(fillRate).roundedDiv(1 ether);
}
buy.amount = buy.amount.sub(tradedWei);
if (buy.amount == 0) {
_removeBuyOrder(buy);
}
sell.amount = sell.amount.sub(tradedTokens);
if (sell.amount == 0) {
_removeSellOrder(sell);
}
augmintToken.transferWithNarrative(buy.maker, tradedTokens, "Buy token order fill");
sell.maker.transfer(tradedWei);
emit OrderFill(buy.maker, sell.maker, buyTokenId,
sellTokenId, publishedRate, price, fillRate, tradedWei, tradedTokens);
return true;
}
function _placeSellTokenOrder(address maker, uint32 price, uint tokenAmount)
private returns (uint64 orderId) {
require(price > 0, "price must be > 0");
require(tokenAmount > 0, "tokenAmount must be > 0");
orderId = ++orderCount;
sellTokenOrders[orderId] = Order(uint64(activeSellOrders.length), maker, price, tokenAmount);
activeSellOrders.push(orderId);
emit NewOrder(orderId, maker, price, tokenAmount, 0);
}
function _removeBuyOrder(Order storage order) private {
_removeOrder(activeBuyOrders, order.index);
}
function _removeSellOrder(Order storage order) private {
_removeOrder(activeSellOrders, order.index);
}
function _removeOrder(uint64[] storage orders, uint64 index) private {
if (index < orders.length - 1) {
orders[index] = orders[orders.length - 1];
}
orders.length--;
}
}
/* Augmint Crypto Euro token (A-EUR) implementation */
contract TokenAEur is AugmintToken {
constructor(address _permissionGranterContract, TransferFeeInterface _feeAccount)
public AugmintToken(_permissionGranterContract, "Augmint Crypto Euro", "AEUR", "EUR", 2, _feeAccount)
{} // solhint-disable-line no-empty-blocks
}
/*
Contract to manage Augmint token loan contracts backed by ETH
For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/loanFlow.png
TODO:
- create MonetarySupervisor interface and use it instead?
- make data arg generic bytes?
- make collect() run as long as gas provided allows
*/
contract LoanManager is Restricted {
using SafeMath for uint256;
uint16 public constant CHUNK_SIZE = 100;
enum LoanState { Open, Repaid, Defaulted, Collected } // NB: Defaulted state is not stored, only getters calculate
struct LoanProduct {
uint minDisbursedAmount; // 0: with decimals set in AugmintToken.decimals
uint32 term; // 1
uint32 discountRate; // 2: discountRate in parts per million , ie. 10,000 = 1%
uint32 collateralRatio; // 3: loan token amount / colleteral pegged ccy value
// in parts per million , ie. 10,000 = 1%
uint32 defaultingFeePt; // 4: % of collateral in parts per million , ie. 50,000 = 5%
bool isActive; // 5
}
/* NB: we don't need to store loan parameters because loan products can't be altered (only disabled/enabled) */
struct LoanData {
uint collateralAmount; // 0
uint repaymentAmount; // 1
address borrower; // 2
uint32 productId; // 3
LoanState state; // 4
uint40 maturity; // 5
}
LoanProduct[] public products;
LoanData[] public loans;
mapping(address => uint[]) public accountLoans; // owner account address => array of loan Ids
Rates public rates; // instance of ETH/pegged currency rate provider contract
AugmintTokenInterface public augmintToken; // instance of token contract
MonetarySupervisor public monetarySupervisor;
event NewLoan(uint32 productId, uint loanId, address indexed borrower, uint collateralAmount, uint loanAmount,
uint repaymentAmount, uint40 maturity);
event LoanProductActiveStateChanged(uint32 productId, bool newState);
event LoanProductAdded(uint32 productId);
event LoanRepayed(uint loanId, address borrower);
event LoanCollected(uint loanId, address indexed borrower, uint collectedCollateral,
uint releasedCollateral, uint defaultingFee);
event SystemContractsChanged(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor);
constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken,
MonetarySupervisor _monetarySupervisor, Rates _rates)
public Restricted(permissionGranterContract) {
augmintToken = _augmintToken;
monetarySupervisor = _monetarySupervisor;
rates = _rates;
}
function addLoanProduct(uint32 term, uint32 discountRate, uint32 collateralRatio, uint minDisbursedAmount,
uint32 defaultingFeePt, bool isActive)
external restrict("StabilityBoard") {
uint _newProductId = products.push(
LoanProduct(minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, isActive)
) - 1;
uint32 newProductId = uint32(_newProductId);
require(newProductId == _newProductId, "productId overflow");
emit LoanProductAdded(newProductId);
}
function setLoanProductActiveState(uint32 productId, bool newState)
external restrict ("StabilityBoard") {
require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason
products[productId].isActive = false;
emit LoanProductActiveStateChanged(productId, newState);
}
function newEthBackedLoan(uint32 productId) external payable {
require(productId < products.length, "invalid productId"); // next line would revert but require to emit reason
LoanProduct storage product = products[productId];
require(product.isActive, "product must be in active state"); // valid product
// calculate loan values based on ETH sent in with Tx
uint tokenValue = rates.convertFromWei(augmintToken.peggedSymbol(), msg.value);
uint repaymentAmount = tokenValue.mul(product.collateralRatio).div(1000000);
uint loanAmount;
(loanAmount, ) = calculateLoanValues(product, repaymentAmount);
require(loanAmount >= product.minDisbursedAmount, "loanAmount must be >= minDisbursedAmount");
uint expiration = now.add(product.term);
uint40 maturity = uint40(expiration);
require(maturity == expiration, "maturity overflow");
// Create new loan
uint loanId = loans.push(LoanData(msg.value, repaymentAmount, msg.sender,
productId, LoanState.Open, maturity)) - 1;
// Store ref to new loan
accountLoans[msg.sender].push(loanId);
// Issue tokens and send to borrower
monetarySupervisor.issueLoan(msg.sender, loanAmount);
emit NewLoan(productId, loanId, msg.sender, msg.value, loanAmount, repaymentAmount, maturity);
}
/* repay loan, called from AugmintToken's transferAndNotify
Flow for repaying loan:
1) user calls token contract's transferAndNotify loanId passed in data arg
2) transferAndNotify transfers tokens to the Lender contract
3) transferAndNotify calls Lender.transferNotification with lockProductId
*/
// from arg is not used as we allow anyone to repay a loan:
function transferNotification(address, uint repaymentAmount, uint loanId) external {
require(msg.sender == address(augmintToken), "msg.sender must be augmintToken");
_repayLoan(loanId, repaymentAmount);
}
function collect(uint[] loanIds) external {
/* when there are a lots of loans to be collected then
the client need to call it in batches to make sure tx won't exceed block gas limit.
Anyone can call it - can't cause harm as it only allows to collect loans which they are defaulted
TODO: optimise defaulting fee calculations
*/
uint totalLoanAmountCollected;
uint totalCollateralToCollect;
uint totalDefaultingFee;
for (uint i = 0; i < loanIds.length; i++) {
require(i < loans.length, "invalid loanId"); // next line would revert but require to emit reason
LoanData storage loan = loans[loanIds[i]];
require(loan.state == LoanState.Open, "loan state must be Open");
require(now >= loan.maturity, "current time must be later than maturity");
LoanProduct storage product = products[loan.productId];
uint loanAmount;
(loanAmount, ) = calculateLoanValues(product, loan.repaymentAmount);
totalLoanAmountCollected = totalLoanAmountCollected.add(loanAmount);
loan.state = LoanState.Collected;
// send ETH collateral to augmintToken reserve
uint defaultingFeeInToken = loan.repaymentAmount.mul(product.defaultingFeePt).div(1000000);
uint defaultingFee = rates.convertToWei(augmintToken.peggedSymbol(), defaultingFeeInToken);
uint targetCollection = rates.convertToWei(augmintToken.peggedSymbol(),
loan.repaymentAmount).add(defaultingFee);
uint releasedCollateral;
if (targetCollection < loan.collateralAmount) {
releasedCollateral = loan.collateralAmount.sub(targetCollection);
loan.borrower.transfer(releasedCollateral);
}
uint collateralToCollect = loan.collateralAmount.sub(releasedCollateral);
if (defaultingFee >= collateralToCollect) {
defaultingFee = collateralToCollect;
collateralToCollect = 0;
} else {
collateralToCollect = collateralToCollect.sub(defaultingFee);
}
totalDefaultingFee = totalDefaultingFee.add(defaultingFee);
totalCollateralToCollect = totalCollateralToCollect.add(collateralToCollect);
emit LoanCollected(loanIds[i], loan.borrower, collateralToCollect.add(defaultingFee), releasedCollateral, defaultingFee);
}
if (totalCollateralToCollect > 0) {
address(monetarySupervisor.augmintReserves()).transfer(totalCollateralToCollect);
}
if (totalDefaultingFee > 0){
address(augmintToken.feeAccount()).transfer(totalDefaultingFee);
}
monetarySupervisor.loanCollectionNotification(totalLoanAmountCollected);// update KPIs
}
/* to allow upgrade of Rates and MonetarySupervisor contracts */
function setSystemContracts(Rates newRatesContract, MonetarySupervisor newMonetarySupervisor)
external restrict("StabilityBoard") {
rates = newRatesContract;
monetarySupervisor = newMonetarySupervisor;
emit SystemContractsChanged(newRatesContract, newMonetarySupervisor);
}
function getProductCount() external view returns (uint ct) {
return products.length;
}
// returns CHUNK_SIZE loan products starting from some offset:
// [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ]
function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) {
for (uint16 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= products.length) { break; }
LoanProduct storage product = products[offset + i];
response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate,
product.collateralRatio, product.defaultingFeePt,
monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ];
}
}
function getLoanCount() external view returns (uint ct) {
return loans.length;
}
/* returns CHUNK_SIZE loans starting from some offset. Loans data encoded as:
[loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime,
loanAmount, interestAmount ] */
function getLoans(uint offset) external view returns (uint[10][CHUNK_SIZE] response) {
for (uint16 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= loans.length) { break; }
response[i] = getLoanTuple(offset + i);
}
}
function getLoanCountForAddress(address borrower) external view returns (uint) {
return accountLoans[borrower].length;
}
/* returns CHUNK_SIZE loans of a given account, starting from some offset. Loans data encoded as:
[loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime,
loanAmount, interestAmount ] */
function getLoansForAddress(address borrower, uint offset) external view returns (uint[10][CHUNK_SIZE] response) {
uint[] storage loansForAddress = accountLoans[borrower];
for (uint16 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= loansForAddress.length) { break; }
response[i] = getLoanTuple(loansForAddress[offset + i]);
}
}
function getLoanTuple(uint loanId) public view returns (uint[10] result) {
require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason
LoanData storage loan = loans[loanId];
LoanProduct storage product = products[loan.productId];
uint loanAmount;
uint interestAmount;
(loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount);
uint disbursementTime = loan.maturity - product.term;
LoanState loanState =
loan.state == LoanState.Open && now >= loan.maturity ? LoanState.Defaulted : loan.state;
result = [loanId, loan.collateralAmount, loan.repaymentAmount, uint(loan.borrower),
loan.productId, uint(loanState), loan.maturity, disbursementTime, loanAmount, interestAmount];
}
function calculateLoanValues(LoanProduct storage product, uint repaymentAmount)
internal view returns (uint loanAmount, uint interestAmount) {
// calculate loan values based on repayment amount
loanAmount = repaymentAmount.mul(product.discountRate).div(1000000);
interestAmount = loanAmount > repaymentAmount ? 0 : repaymentAmount.sub(loanAmount);
}
/* internal function, assuming repayment amount already transfered */
function _repayLoan(uint loanId, uint repaymentAmount) internal {
require(loanId < loans.length, "invalid loanId"); // next line would revert but require to emit reason
LoanData storage loan = loans[loanId];
require(loan.state == LoanState.Open, "loan state must be Open");
require(repaymentAmount == loan.repaymentAmount, "repaymentAmount must be equal to tokens sent");
require(now <= loan.maturity, "current time must be earlier than maturity");
LoanProduct storage product = products[loan.productId];
uint loanAmount;
uint interestAmount;
(loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount);
loans[loanId].state = LoanState.Repaid;
if (interestAmount > 0) {
augmintToken.transfer(monetarySupervisor.interestEarnedAccount(), interestAmount);
augmintToken.burn(loanAmount);
} else {
// negative or zero interest (i.e. discountRate >= 0)
augmintToken.burn(repaymentAmount);
}
monetarySupervisor.loanRepaymentNotification(loanAmount); // update KPIs
loan.borrower.transfer(loan.collateralAmount); // send back ETH collateral
emit LoanRepayed(loanId, loan.borrower);
}
}
/* contract for tracking locked funds
requirements
-> lock funds
-> unlock funds
-> index locks by address
For flows see: https://github.com/Augmint/augmint-contracts/blob/master/docs/lockFlow.png
TODO / think about:
-> self-destruct function?
*/
contract Locker is Restricted, TokenReceiver {
using SafeMath for uint256;
uint public constant CHUNK_SIZE = 100;
event NewLockProduct(uint32 indexed lockProductId, uint32 perTermInterest, uint32 durationInSecs,
uint32 minimumLockAmount, bool isActive);
event LockProductActiveChange(uint32 indexed lockProductId, bool newActiveState);
// NB: amountLocked includes the original amount, plus interest
event NewLock(address indexed lockOwner, uint lockId, uint amountLocked, uint interestEarned,
uint40 lockedUntil, uint32 perTermInterest, uint32 durationInSecs);
event LockReleased(address indexed lockOwner, uint lockId);
event MonetarySupervisorChanged(MonetarySupervisor newMonetarySupervisor);
struct LockProduct {
// perTermInterest is in millionths (i.e. 1,000,000 = 100%):
uint32 perTermInterest;
uint32 durationInSecs;
uint32 minimumLockAmount;
bool isActive;
}
/* NB: we don't need to store lock parameters because lockProducts can't be altered (only disabled/enabled) */
struct Lock {
uint amountLocked;
address owner;
uint32 productId;
uint40 lockedUntil;
bool isActive;
}
AugmintTokenInterface public augmintToken;
MonetarySupervisor public monetarySupervisor;
LockProduct[] public lockProducts;
Lock[] public locks;
// lock ids for an account
mapping(address => uint[]) public accountLocks;
constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken,
MonetarySupervisor _monetarySupervisor)
public Restricted(permissionGranterContract) {
augmintToken = _augmintToken;
monetarySupervisor = _monetarySupervisor;
}
function addLockProduct(uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive)
external restrict("StabilityBoard") {
uint _newLockProductId = lockProducts.push(
LockProduct(perTermInterest, durationInSecs, minimumLockAmount, isActive)) - 1;
uint32 newLockProductId = uint32(_newLockProductId);
require(newLockProductId == _newLockProductId, "lockProduct overflow");
emit NewLockProduct(newLockProductId, perTermInterest, durationInSecs, minimumLockAmount, isActive);
}
function setLockProductActiveState(uint32 lockProductId, bool isActive) external restrict("StabilityBoard") {
// next line would revert but require to emit reason:
require(lockProductId < lockProducts.length, "invalid lockProductId");
lockProducts[lockProductId].isActive = isActive;
emit LockProductActiveChange(lockProductId, isActive);
}
/* lock funds, called from AugmintToken's transferAndNotify
Flow for locking tokens:
1) user calls token contract's transferAndNotify lockProductId passed in data arg
2) transferAndNotify transfers tokens to the Lock contract
3) transferAndNotify calls Lock.transferNotification with lockProductId
*/
function transferNotification(address from, uint256 amountToLock, uint _lockProductId) external {
require(msg.sender == address(augmintToken), "msg.sender must be augmintToken");
// next line would revert but require to emit reason:
require(lockProductId < lockProducts.length, "invalid lockProductId");
uint32 lockProductId = uint32(_lockProductId);
require(lockProductId == _lockProductId, "lockProductId overflow");
/* TODO: make data arg generic bytes
uint productId;
assembly { // solhint-disable-line no-inline-assembly
productId := mload(data)
} */
_createLock(lockProductId, from, amountToLock);
}
function releaseFunds(uint lockId) external {
// next line would revert but require to emit reason:
require(lockId < locks.length, "invalid lockId");
Lock storage lock = locks[lockId];
LockProduct storage lockProduct = lockProducts[lock.productId];
require(lock.isActive, "lock must be in active state");
require(now >= lock.lockedUntil, "current time must be later than lockedUntil");
lock.isActive = false;
uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked);
monetarySupervisor.releaseFundsNotification(lock.amountLocked); // to maintain totalLockAmount
augmintToken.transferWithNarrative(lock.owner, lock.amountLocked.add(interestEarned),
"Funds released from lock");
emit LockReleased(lock.owner, lockId);
}
function setMonetarySupervisor(MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") {
monetarySupervisor = newMonetarySupervisor;
emit MonetarySupervisorChanged(newMonetarySupervisor);
}
function getLockProductCount() external view returns (uint) {
return lockProducts.length;
}
// returns 20 lock products starting from some offset
// lock products are encoded as [ perTermInterest, durationInSecs, minimumLockAmount, maxLockAmount, isActive ]
function getLockProducts(uint offset) external view returns (uint[5][CHUNK_SIZE] response) {
for (uint8 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= lockProducts.length) { break; }
LockProduct storage lockProduct = lockProducts[offset + i];
response[i] = [ lockProduct.perTermInterest, lockProduct.durationInSecs, lockProduct.minimumLockAmount,
monetarySupervisor.getMaxLockAmount(lockProduct.minimumLockAmount, lockProduct.perTermInterest),
lockProduct.isActive ? 1 : 0 ];
}
}
function getLockCount() external view returns (uint) {
return locks.length;
}
function getLockCountForAddress(address lockOwner) external view returns (uint) {
return accountLocks[lockOwner].length;
}
// returns CHUNK_SIZE locks starting from some offset
// lock products are encoded as
// [lockId, owner, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ]
// NB: perTermInterest is in millionths (i.e. 1,000,000 = 100%):
function getLocks(uint offset) external view returns (uint[8][CHUNK_SIZE] response) {
for (uint16 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= locks.length) { break; }
Lock storage lock = locks[offset + i];
LockProduct storage lockProduct = lockProducts[lock.productId];
uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked);
response[i] = [uint(offset + i), uint(lock.owner), lock.amountLocked, interestEarned, lock.lockedUntil,
lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0];
}
}
// returns CHUNK_SIZE locks of a given account, starting from some offset
// lock products are encoded as
// [lockId, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ]
function getLocksForAddress(address lockOwner, uint offset) external view returns (uint[7][CHUNK_SIZE] response) {
uint[] storage locksForAddress = accountLocks[lockOwner];
for (uint16 i = 0; i < CHUNK_SIZE; i++) {
if (offset + i >= locksForAddress.length) { break; }
Lock storage lock = locks[locksForAddress[offset + i]];
LockProduct storage lockProduct = lockProducts[lock.productId];
uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked);
response[i] = [ locksForAddress[offset + i], lock.amountLocked, interestEarned, lock.lockedUntil,
lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0 ];
}
}
function calculateInterest(uint32 perTermInterest, uint amountToLock) public pure returns (uint interestEarned) {
interestEarned = amountToLock.mul(perTermInterest).div(1000000);
}
// Internal function. assumes amountToLock is already transferred to this Lock contract
function _createLock(uint32 lockProductId, address lockOwner, uint amountToLock) internal returns(uint lockId) {
LockProduct storage lockProduct = lockProducts[lockProductId];
require(lockProduct.isActive, "lockProduct must be in active state");
require(amountToLock >= lockProduct.minimumLockAmount, "amountToLock must be >= minimumLockAmount");
uint interestEarned = calculateInterest(lockProduct.perTermInterest, amountToLock);
uint expiration = now.add(lockProduct.durationInSecs);
uint40 lockedUntil = uint40(expiration);
require(lockedUntil == expiration, "lockedUntil overflow");
lockId = locks.push(Lock(amountToLock, lockOwner, lockProductId, lockedUntil, true)) - 1;
accountLocks[lockOwner].push(lockId);
monetarySupervisor.requestInterest(amountToLock, interestEarned); // update KPIs & transfer interest here
emit NewLock(lockOwner, lockId, amountToLock, interestEarned, lockedUntil, lockProduct.perTermInterest,
lockProduct.durationInSecs);
}
} | called via StabilityBoardProxy preToken Permissions StabilityBoard RatesFeeder permissions to allow calling setRate() set NoTransferFee permissions set MonetarySupervisor permissions set LoanManager permissions set Locker permissions term (in sec), discountRate, loanCoverageRatio, minDisbursedAmount (w/ 4 decimals), defaultingFeePt, isActive (perTermInterest, durationInSecs, minimumLockAmount, isActive) | function execute(Main0001_initFirstDeploy /* self, not used */) external {
require(address(this) == stabilityBoardProxyAddress, "only deploy via stabilityboardsigner");
preTokenPermissions[0] = "PreTokenSigner";
preTokenPermissions[1] = "PermissionGranter";
preToken.grantMultiplePermissions(preTokenProxyAddress, preTokenPermissions);
rates.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
feeAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
interestEarnedAccount.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
tokenAEur.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
augmintReserves.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
monetarySupervisor.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
loanManager.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
locker.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
exchange.grantPermission(stabilityBoardProxyAddress, "StabilityBoard");
rates.grantPermission(RATES_FEEDER_ACCOUNT, "RatesFeeder");
feeAccount.grantPermission(feeAccount, "NoTransferFee");
feeAccount.grantPermission(augmintReserves, "NoTransferFee");
feeAccount.grantPermission(interestEarnedAccount, "NoTransferFee");
feeAccount.grantPermission(monetarySupervisor, "NoTransferFee");
feeAccount.grantPermission(loanManager, "NoTransferFee");
feeAccount.grantPermission(locker, "NoTransferFee");
feeAccount.grantPermission(exchange, "NoTransferFee");
interestEarnedAccount.grantPermission(monetarySupervisor, "MonetarySupervisor");
tokenAEur.grantPermission(monetarySupervisor, "MonetarySupervisor");
augmintReserves.grantPermission(monetarySupervisor, "MonetarySupervisor");
monetarySupervisor.grantPermission(loanManager, "LoanManager");
monetarySupervisor.grantPermission(locker, "Locker");
preToken.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
rates.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
feeAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
augmintReserves.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
interestEarnedAccount.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
tokenAEur.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
monetarySupervisor.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
loanManager.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
locker.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
exchange.revokePermission(DEPLOYER_ACCOUNT, "PermissionGranter");
preToken.revokePermission(stabilityBoardProxyAddress, "PermissionGranter");
| 7,655,185 |
/**
*Submitted for verification at Etherscan.io on 2020-05-27
*/
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/**
* @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;
}
}
/**
Note: Simple contract to use as base for const vals
*/
contract CommonConstants {
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 internal constant ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the batch transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _ids An array containing ids of each token being transferred (order and length must match _values array)
@param _values An array containing amounts of each token being transferred (order and length must match _ids array)
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns (bytes4);
}
/**
* @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);
}
/**
@title ERC-1155 Multi Token Standard
@dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
contract IERC1155 is IERC165 {
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _value
);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _values
);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled).
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes calldata _data
) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account)
internal
pure
returns (address payable)
{
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
}
// A sample implementation of core ERC1155 function.
contract ERC1155 is IERC1155, ERC165, CommonConstants {
using SafeMath for uint256;
using Address for address;
// id => (owner => balance)
mapping(uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping(address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////
constructor() public {
_registerInterface(INTERFACE_SIGNATURE_ERC1155);
}
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes calldata _data
) external {
require(_to != address(0x0), "_to must be non-zero.");
require(
_from == msg.sender || operatorApproval[_from][msg.sender] == true,
"Need operator approval for 3rd party transfers."
);
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(
msg.sender,
_from,
_to,
_id,
_value,
_data
);
}
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external {
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(
_ids.length == _values.length,
"_ids and _values array lenght must match."
);
require(
_from == msg.sender || operatorApproval[_from][msg.sender] == true,
"Need operator approval for 3rd party transfers."
);
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
// Now that the balances are updated and the events are emitted,
// call onERC1155BatchReceived if the destination is a contract.
if (_to.isContract()) {
_doSafeBatchTransferAcceptanceCheck(
msg.sender,
_from,
_to,
_ids,
_values,
_data
);
}
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256)
{
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory)
{
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool)
{
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(
address _operator,
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes memory _data
) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(
ERC1155TokenReceiver(_to).onERC1155Received(
_operator,
_from,
_id,
_value,
_data
) == ERC1155_ACCEPTED,
"contract returned an unknown value from onERC1155Received"
);
}
function _doSafeBatchTransferAcceptanceCheck(
address _operator,
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _values,
bytes memory _data
) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(
ERC1155TokenReceiver(_to).onERC1155BatchReceived(
_operator,
_from,
_ids,
_values,
_data
) == ERC1155_BATCH_ACCEPTED,
"contract returned an unknown value from onERC1155BatchReceived"
);
}
}
library UintLibrary {
function toString(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
library StringLibrary {
using UintLibrary for uint256;
function append(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
function append(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory bbb = new bytes(_ba.length + _bb.length + _bc.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bbb[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bbb[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) bbb[k++] = _bc[i];
return string(bbb);
}
function recover(
string memory message,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
bytes memory msgBytes = bytes(message);
bytes memory fullMessage = concat(
bytes("\x19Ethereum Signed Message:\n"),
bytes(msgBytes.length.toString()),
msgBytes,
new bytes(0),
new bytes(0),
new bytes(0),
new bytes(0)
);
return ecrecover(keccak256(fullMessage), v, r, s);
}
function concat(
bytes memory _ba,
bytes memory _bb,
bytes memory _bc,
bytes memory _bd,
bytes memory _be,
bytes memory _bf,
bytes memory _bg
) internal pure returns (bytes memory) {
bytes memory resultBytes = new bytes(
_ba.length +
_bb.length +
_bc.length +
_bd.length +
_be.length +
_bf.length +
_bg.length
);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) resultBytes[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) resultBytes[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) resultBytes[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) resultBytes[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) resultBytes[k++] = _be[i];
for (uint256 i = 0; i < _bf.length; i++) resultBytes[k++] = _bf[i];
for (uint256 i = 0; i < _bg.length; i++) resultBytes[k++] = _bg[i];
return resultBytes;
}
}
contract HasContractURI is ERC165 {
string public contractURI;
/*
* bytes4(keccak256('contractURI()')) == 0xe8a3d485
*/
bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
constructor(string memory _contractURI) public {
contractURI = _contractURI;
_registerInterface(_INTERFACE_ID_CONTRACT_URI);
}
/**
* @dev Internal function to set the contract URI
* @param _contractURI string URI prefix to assign
*/
function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
}
contract HasTokenURI {
using StringLibrary for string;
//Token URI prefix
string public tokenURIPrefix;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
constructor(string memory _tokenURIPrefix) public {
tokenURIPrefix = _tokenURIPrefix;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
return tokenURIPrefix.append(_tokenURIs[tokenId]);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to set the token URI prefix.
* @param _tokenURIPrefix string URI prefix to assign
*/
function _setTokenURIPrefix(string memory _tokenURIPrefix) internal {
tokenURIPrefix = _tokenURIPrefix;
}
function _clearTokenURI(uint256 tokenId) internal {
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
Note: The ERC-165 identifier for this interface is 0x0e89341c.
*/
interface IERC1155Metadata_URI {
/**
@notice A distinct Uniform Resource Identifier (URI) for a given token.
@dev URIs are defined in RFC 3986.
The URI may point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
@return URI string
*/
function uri(uint256 _id) external view returns (string memory);
}
/**
Note: The ERC-165 identifier for this interface is 0x0e89341c.
*/
contract ERC1155Metadata_URI is IERC1155Metadata_URI, HasTokenURI {
constructor(string memory _tokenURIPrefix)
public
HasTokenURI(_tokenURIPrefix)
{}
function uri(uint256 _id) external view returns (string memory) {
return _tokenURI(_id);
}
}
contract HasSecondarySaleFees is ERC165 {
event SecondarySaleFees(
uint256 tokenId,
address[] recipients,
uint256[] bps
);
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
constructor() public {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory);
function getFeeBps(uint256 id) public view returns (uint256[] memory);
}
contract ERC1155Base is
HasSecondarySaleFees,
Ownable,
ERC1155Metadata_URI,
HasContractURI,
ERC1155
{
struct Fee {
address payable recipient;
uint256 value;
}
// id => creator
mapping(uint256 => address) public creators;
// id => fees
mapping(uint256 => Fee[]) public fees;
constructor(string memory contractURI, string memory tokenURIPrefix)
public
HasContractURI(contractURI)
ERC1155Metadata_URI(tokenURIPrefix)
{}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory)
{
Fee[] memory _fees = fees[id];
address payable[] memory result = new address payable[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].recipient;
}
return result;
}
function getFeeBps(uint256 id) public view returns (uint256[] memory) {
Fee[] memory _fees = fees[id];
uint256[] memory result = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].value;
}
return result;
}
// Creates a new token type and assings _initialSupply to minter
function _mint(
uint256 _id,
Fee[] memory _fees,
uint256 _supply,
string memory _uri
) internal {
require(creators[_id] == address(0x0), "Token is already minted");
require(_supply != 0, "Supply should be positive");
require(bytes(_uri).length > 0, "uri should be set");
creators[_id] = msg.sender;
address[] memory recipients = new address[](_fees.length);
uint256[] memory bps = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
require(
_fees[i].recipient != address(0x0),
"Recipient should be present"
);
require(_fees[i].value != 0, "Fee value should be positive");
fees[_id].push(_fees[i]);
recipients[i] = _fees[i].recipient;
bps[i] = _fees[i].value;
}
if (_fees.length > 0) {
emit SecondarySaleFees(_id, recipients, bps);
}
balances[_id][msg.sender] = _supply;
_setTokenURI(_id, _uri);
// Transfer event with mint semantic
emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _supply);
emit URI(_uri, _id);
}
function burn(
address _owner,
uint256 _id,
uint256 _value
) external {
require(
_owner == msg.sender ||
operatorApproval[_owner][msg.sender] == true,
"Need operator approval for 3rd party burns."
);
// SafeMath will throw with insuficient funds _owner
// or if _id is not valid (balance will be 0)
balances[_id][_owner] = balances[_id][_owner].sub(_value);
// MUST emit event
emit TransferSingle(msg.sender, _owner, address(0x0), _id, _value);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(
creators[tokenId] != address(0x0),
"_setTokenURI: Token should exist"
);
super._setTokenURI(tokenId, uri);
}
function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner {
_setTokenURIPrefix(tokenURIPrefix);
}
function setContractURI(string memory contractURI) public onlyOwner {
_setContractURI(contractURI);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
// library Roles {
// struct Role {
// mapping (address => bool) bearer;
// }
// /**
// * @dev Give an account access to this role.
// */
// function add(Role storage role, address account) internal {
// require(!has(role, account), "Roles: account already has role");
// role.bearer[account] = true;
// }
// /**
// * @dev Remove an account's access to this role.
// */
// function remove(Role storage role, address account) internal {
// require(has(role, account), "Roles: account does not have role");
// role.bearer[account] = false;
// }
// /**
// * @dev Check if an account has this role.
// * @return bool
// */
// function has(Role storage role, address account) internal view returns (bool) {
// require(account != address(0), "Roles: account is the zero address");
// return role.bearer[account];
// }
// }
// contract SignerRole is Context {
// using Roles for Roles.Role;
// event SignerAdded(address indexed account);
// event SignerRemoved(address indexed account);
// Roles.Role private _signers;
// constructor () internal {
// _addSigner(_msgSender());
// }
// modifier onlySigner() {
// require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
// _;
// }
// function isSigner(address account) public view returns (bool) {
// return _signers.has(account);
// }
// function addSigner(address account) public onlySigner {
// _addSigner(account);
// }
// function renounceSigner() public {
// _removeSigner(_msgSender());
// }
// function _addSigner(address account) internal {
// _signers.add(account);
// emit SignerAdded(account);
// }
// function _removeSigner(address account) internal {
// _signers.remove(account);
// emit SignerRemoved(account);
// }
// }
contract SwaggaToken is Ownable, ERC1155Base {
event WhiteListAdded(address indexed account);
event WhiteListRemoved(address indexed account);
mapping(address => bool) public whiteList;
string public name;
string public symbol;
modifier onlyWhiteList {
require(whiteList[msg.sender], "whiteList only");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory contractURI,
string memory tokenURIPrefix
) public ERC1155Base(contractURI, tokenURIPrefix) {
name = _name;
symbol = _symbol;
whiteList[_msgSender()] = true;
_registerInterface(bytes4(keccak256("MINT_WITH_ADDRESS")));
}
function addWhiteList(address account) public onlyOwner {
whiteList[account] = true;
emit WhiteListAdded(account);
}
function removeWhiteList(address account) public onlyOwner {
whiteList[account] = false;
emit WhiteListRemoved(account);
}
function mint(
uint256 id,
Fee[] memory fees,
uint256 supply,
string memory uri
) public onlyWhiteList {
//require(isSigner(ecrecover(keccak256(abi.encodePacked(this, id)), v, r, s)), "signer should sign tokenId");
_mint(id, fees, supply, uri);
}
} | require(isSigner(ecrecover(keccak256(abi.encodePacked(this, id)), v, r, s)), "signer should sign tokenId"); | function mint(
uint256 id,
Fee[] memory fees,
uint256 supply,
string memory uri
) public onlyWhiteList {
_mint(id, fees, supply, uri);
}
| 12,205,527 |
./full_match/80001/0x78B356Eb7c200ec9fFb90D5f1a230832141f8418/sources/contracts/Swap.sol | - Deposit to a tranche | function makeDeposit (uint CTMq, uint USDCq, uint16 trancheNumber) private {
tranche[] memory _tranches = tranches;
depositXaction memory dX= depositXaction(
CTMq,
USDCq,
block.timestamp,
_tranches[trancheNumber].lockDuration,
_tranches[trancheNumber].price,
trancheNumber,
false,
false);
DepositRecord[msg.sender].push(dX);
}
| 867,029 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import '@openzeppelin/contracts/utils/SafeCast.sol';
import "./interface/IERC20Extended.sol";
import "./interface/IFeeCalculator.sol";
import "./interface/IFlashLoanReceiver.sol";
import "./interface/IPremiaReferral.sol";
import "./interface/IPremiaUncutErc20.sol";
import "./uniswapV2/interfaces/IUniswapV2Router02.sol";
/// @author Premia
/// @title An option contract
contract PremiaOption is Ownable, ERC1155, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct OptionWriteArgs {
address token; // Token address
uint256 amount; // Amount of tokens to write option for
uint256 strikePrice; // Strike price (Must follow strikePriceIncrement of token)
uint256 expiration; // Expiration timestamp of the option (Must follow expirationIncrement)
bool isCall; // If true : Call option | If false : Put option
}
struct OptionData {
address token; // Token address
uint256 strikePrice; // Strike price (Must follow strikePriceIncrement of token)
uint256 expiration; // Expiration timestamp of the option (Must follow expirationIncrement)
bool isCall; // If true : Call option | If false : Put option
uint256 claimsPreExp; // Amount of options from which the funds have been withdrawn pre expiration
uint256 claimsPostExp; // Amount of options from which the funds have been withdrawn post expiration
uint256 exercised; // Amount of options which have been exercised
uint256 supply; // Total circulating supply
uint8 decimals; // Token decimals
}
// Total write cost = collateral + fee + feeReferrer
struct QuoteWrite {
address collateralToken; // The token to deposit as collateral
uint256 collateral; // The amount of collateral to deposit
uint8 collateralDecimals; // Decimals of collateral token
uint256 fee; // The amount of collateralToken needed to be paid as protocol fee
uint256 feeReferrer; // The amount of collateralToken which will be paid the referrer
}
// Total exercise cost = input + fee + feeReferrer
struct QuoteExercise {
address inputToken; // Input token for exercise
uint256 input; // Amount of input token to pay to exercise
uint8 inputDecimals; // Decimals of input token
address outputToken; // Output token from the exercise
uint256 output; // Amount of output tokens which will be received on exercise
uint8 outputDecimals; // Decimals of output token
uint256 fee; // The amount of inputToken needed to be paid as protocol fee
uint256 feeReferrer; // The amount of inputToken which will be paid to the referrer
}
struct Pool {
uint256 tokenAmount; // The amount of tokens in the option pool
uint256 denominatorAmount; // The amounts of denominator in the option pool
}
IERC20 public denominator;
uint8 public denominatorDecimals;
//////////////////////////////////////////////////
// Address receiving protocol fees (PremiaMaker)
address public feeRecipient;
// PremiaReferral contract
IPremiaReferral public premiaReferral;
// The uPremia token
IPremiaUncutErc20 public uPremia;
// FeeCalculator contract
IFeeCalculator public feeCalculator;
//////////////////////////////////////////////////
// Whitelisted tokens for which options can be written (Each token must also have a non 0 strike price increment to be enabled)
address[] public tokens;
// Strike price increment mapping of each token
mapping (address => uint256) public tokenStrikeIncrement;
//////////////////////////////////////////////////
// The option id of next option type which will be created
uint256 public nextOptionId = 1;
// Offset to add to Unix timestamp to make it Fri 23:59:59 UTC
uint256 private constant _baseExpiration = 172799;
// Expiration increment
uint256 private constant _expirationIncrement = 1 weeks;
// Max expiration time from now
uint256 public maxExpiration = 365 days;
// Uniswap routers allowed to be used for swap from flashExercise
address[] public whitelistedUniswapRouters;
// token => expiration => strikePrice => isCall (1 for call, 0 for put) => optionId
mapping (address => mapping(uint256 => mapping(uint256 => mapping (bool => uint256)))) public options;
// optionId => OptionData
mapping (uint256 => OptionData) public optionData;
// optionId => Pool
mapping (uint256 => Pool) public pools;
// account => optionId => amount of options written
mapping (address => mapping (uint256 => uint256)) public nbWritten;
////////////
// Events //
////////////
event SetToken(address indexed token, uint256 strikePriceIncrement);
event OptionIdCreated(uint256 indexed optionId, address indexed token);
event OptionWritten(address indexed owner, uint256 indexed optionId, address indexed token, uint256 amount);
event OptionCancelled(address indexed owner, uint256 indexed optionId, address indexed token, uint256 amount);
event OptionExercised(address indexed user, uint256 indexed optionId, address indexed token, uint256 amount);
event Withdraw(address indexed user, uint256 indexed optionId, address indexed token, uint256 amount);
event FeePaid(address indexed user, address indexed token, address indexed referrer, uint256 feeProtocol, uint256 feeReferrer);
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
/// @param _uri URI of ERC1155 metadata
/// @param _denominator The token used as denominator
/// @param _uPremia The uPremia token
/// @param _feeCalculator FeeCalculator contract
/// @param _premiaReferral PremiaReferral contract
/// @param _feeRecipient Recipient of protocol fees (PremiaMaker)
constructor(string memory _uri, IERC20 _denominator, IPremiaUncutErc20 _uPremia, IFeeCalculator _feeCalculator,
IPremiaReferral _premiaReferral, address _feeRecipient) ERC1155(_uri) {
denominator = _denominator;
uPremia = _uPremia;
feeCalculator = _feeCalculator;
feeRecipient = _feeRecipient;
premiaReferral = _premiaReferral;
denominatorDecimals = IERC20Extended(address(_denominator)).decimals();
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
///////////////
// Modifiers //
///////////////
modifier notExpired(uint256 _optionId) {
require(block.timestamp < optionData[_optionId].expiration, "Expired");
_;
}
modifier expired(uint256 _optionId) {
require(block.timestamp >= optionData[_optionId].expiration, "Not expired");
_;
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
///////////
// Admin //
///////////
/// @notice Set new URI for ERC1155 metadata
/// @param _newUri The new URI
function setURI(string memory _newUri) external onlyOwner {
_setURI(_newUri);
}
/// @notice Set new protocol fee recipient
/// @param _feeRecipient The new protocol fee recipient
function setFeeRecipient(address _feeRecipient) external onlyOwner {
feeRecipient = _feeRecipient;
}
/// @notice Set a new max expiration date for options writing (By default, 1 year from current date)
/// @param _max The max amount of seconds in the future for which an option expiration can be set
function setMaxExpiration(uint256 _max) external onlyOwner {
maxExpiration = _max;
}
/// @notice Set a new PremiaReferral contract
/// @param _premiaReferral The new PremiaReferral Contract
function setPremiaReferral(IPremiaReferral _premiaReferral) external onlyOwner {
premiaReferral = _premiaReferral;
}
/// @notice Set a new PremiaUncut contract
/// @param _uPremia The new PremiaUncut Contract
function setPremiaUncutErc20(IPremiaUncutErc20 _uPremia) external onlyOwner {
uPremia = _uPremia;
}
/// @notice Set a new FeeCalculator contract
/// @param _feeCalculator The new FeeCalculator Contract
function setFeeCalculator(IFeeCalculator _feeCalculator) external onlyOwner {
feeCalculator = _feeCalculator;
}
/// @notice Set settings for tokens to support writing of options paired to denominator
/// @dev A value of 0 means this token is disabled and options cannot be written for it
/// @param _tokens The list of tokens for which to set strike price increment
/// @param _strikePriceIncrement The new strike price increment to set for each token
function setTokens(address[] memory _tokens, uint256[] memory _strikePriceIncrement) external onlyOwner {
require(_tokens.length == _strikePriceIncrement.length);
for (uint256 i=0; i < _tokens.length; i++) {
if (!_isInArray(_tokens[i], tokens)) {
tokens.push(_tokens[i]);
}
require(_tokens[i] != address(denominator), "Cant add denominator");
tokenStrikeIncrement[_tokens[i]] = _strikePriceIncrement[i];
emit SetToken(_tokens[i], _strikePriceIncrement[i]);
}
}
/// @notice Set a new list of whitelisted UniswapRouter contracts allowed to be used for flashExercise
/// @param _addrList The new list of whitelisted routers
function setWhitelistedUniswapRouters(address[] memory _addrList) external onlyOwner {
delete whitelistedUniswapRouters;
for (uint256 i=0; i < _addrList.length; i++) {
whitelistedUniswapRouters.push(_addrList[i]);
}
}
//////////////////////////////////////////////////
//////////
// View //
//////////
/// @notice Get the id of an option
/// @param _token Token for which the option is for
/// @param _expiration Expiration timestamp of the option
/// @param _strikePrice Strike price of the option
/// @param _isCall Whether the option is a call or a put
/// @return The option id
function getOptionId(address _token, uint256 _expiration, uint256 _strikePrice, bool _isCall) public view returns(uint256) {
return options[_token][_expiration][_strikePrice][_isCall];
}
/// @notice Get the amount of whitelisted tokens
/// @return The amount of whitelisted tokens
function tokensLength() external view returns(uint256) {
return tokens.length;
}
/// @notice Get a quote to write an option
/// @param _from Address which will write the option
/// @param _option The option to write
/// @param _referrer Referrer
/// @param _decimals The option token decimals
/// @return The quote
function getWriteQuote(address _from, OptionWriteArgs memory _option, address _referrer, uint8 _decimals) public view returns(QuoteWrite memory) {
QuoteWrite memory quote;
if (_option.isCall) {
quote.collateralToken = _option.token;
quote.collateral = _option.amount;
quote.collateralDecimals = _decimals;
} else {
quote.collateralToken = address(denominator);
quote.collateral = _option.amount.mul(_option.strikePrice).div(10**_decimals);
quote.collateralDecimals = denominatorDecimals;
}
(uint256 fee, uint256 feeReferrer) = feeCalculator.getFeeAmounts(_from, _referrer != address(0), quote.collateral, IFeeCalculator.FeeType.Write);
quote.fee = fee;
quote.feeReferrer = feeReferrer;
return quote;
}
/// @notice Get a quote to exercise an option
/// @param _from Address which will exercise the option
/// @param _option The option to exercise
/// @param _referrer Referrer
/// @param _decimals The option token decimals
/// @return The quote
function getExerciseQuote(address _from, OptionData memory _option, uint256 _amount, address _referrer, uint8 _decimals) public view returns(QuoteExercise memory) {
QuoteExercise memory quote;
uint256 tokenAmount = _amount;
uint256 denominatorAmount = _amount.mul(_option.strikePrice).div(10**_decimals);
if (_option.isCall) {
quote.inputToken = address(denominator);
quote.input = denominatorAmount;
quote.inputDecimals = denominatorDecimals;
quote.outputToken = _option.token;
quote.output = tokenAmount;
quote.outputDecimals = _option.decimals;
} else {
quote.inputToken = _option.token;
quote.input = tokenAmount;
quote.inputDecimals = _option.decimals;
quote.outputToken = address(denominator);
quote.output = denominatorAmount;
quote.outputDecimals = denominatorDecimals;
}
(uint256 fee, uint256 feeReferrer) = feeCalculator.getFeeAmounts(_from, _referrer != address(0), quote.input, IFeeCalculator.FeeType.Exercise);
quote.fee = fee;
quote.feeReferrer = feeReferrer;
return quote;
}
//////////////////////////////////////////////////
//////////
// Main //
//////////
/// @notice Get the id of the option, or create a new id if there is no existing id for it
/// @param _token Token for which the option is for
/// @param _expiration Expiration timestamp of the option
/// @param _strikePrice Strike price of the option
/// @param _isCall Whether the option is a call or a put
/// @return The option id
function getOptionIdOrCreate(address _token, uint256 _expiration, uint256 _strikePrice, bool _isCall) public returns(uint256) {
uint256 optionId = getOptionId(_token, _expiration, _strikePrice, _isCall);
if (optionId == 0) {
_preCheckOptionIdCreate(_token, _strikePrice, _expiration);
optionId = nextOptionId;
options[_token][_expiration][_strikePrice][_isCall] = optionId;
uint8 decimals = IERC20Extended(_token).decimals();
require(decimals <= 18, "Too many decimals");
pools[optionId] = Pool({ tokenAmount: 0, denominatorAmount: 0 });
optionData[optionId] = OptionData({
token: _token,
expiration: _expiration,
strikePrice: _strikePrice,
isCall: _isCall,
claimsPreExp: 0,
claimsPostExp: 0,
exercised: 0,
supply: 0,
decimals: decimals
});
emit OptionIdCreated(optionId, _token);
nextOptionId = nextOptionId.add(1);
}
return optionId;
}
//////////////////////////////////////////////////
/// @notice Write an option on behalf of an address with an existing option id (Used by market delayed writing)
/// @dev Requires approval on option contract + token needed to write the option
/// @param _from Address on behalf of which the option is written
/// @param _optionId The id of the option to write
/// @param _amount Amount of options to write
/// @param _referrer Referrer
/// @return The option id
function writeOptionWithIdFrom(address _from, uint256 _optionId, uint256 _amount, address _referrer) external returns(uint256) {
require(isApprovedForAll(_from, msg.sender), "Not approved");
OptionData memory data = optionData[_optionId];
OptionWriteArgs memory writeArgs = OptionWriteArgs({
token: data.token,
amount: _amount,
strikePrice: data.strikePrice,
expiration: data.expiration,
isCall: data.isCall
});
return _writeOption(_from, writeArgs, _referrer);
}
/// @notice Write an option on behalf of an address
/// @dev Requires approval on option contract + token needed to write the option
/// @param _from Address on behalf of which the option is written
/// @param _option The option to write
/// @param _referrer Referrer
/// @return The option id
function writeOptionFrom(address _from, OptionWriteArgs memory _option, address _referrer) external returns(uint256) {
require(isApprovedForAll(_from, msg.sender), "Not approved");
return _writeOption(_from, _option, _referrer);
}
/// @notice Write an option
/// @param _option The option to write
/// @param _referrer Referrer
/// @return The option id
function writeOption(OptionWriteArgs memory _option, address _referrer) public returns(uint256) {
return _writeOption(msg.sender, _option, _referrer);
}
/// @notice Write an option on behalf of an address
/// @param _from Address on behalf of which the option is written
/// @param _option The option to write
/// @param _referrer Referrer
/// @return The option id
function _writeOption(address _from, OptionWriteArgs memory _option, address _referrer) internal nonReentrant returns(uint256) {
require(_option.amount > 0, "Amount <= 0");
uint256 optionId = getOptionIdOrCreate(_option.token, _option.expiration, _option.strikePrice, _option.isCall);
// Set referrer or get current if one already exists
_referrer = _trySetReferrer(_from, _referrer);
QuoteWrite memory quote = getWriteQuote(_from, _option, _referrer, optionData[optionId].decimals);
IERC20(quote.collateralToken).safeTransferFrom(_from, address(this), quote.collateral);
_payFees(_from, IERC20(quote.collateralToken), _referrer, quote.fee, quote.feeReferrer, quote.collateralDecimals);
if (_option.isCall) {
pools[optionId].tokenAmount = pools[optionId].tokenAmount.add(quote.collateral);
} else {
pools[optionId].denominatorAmount = pools[optionId].denominatorAmount.add(quote.collateral);
}
nbWritten[_from][optionId] = nbWritten[_from][optionId].add(_option.amount);
mint(_from, optionId, _option.amount);
emit OptionWritten(_from, optionId, _option.token, _option.amount);
return optionId;
}
//////////////////////////////////////////////////
/// @notice Cancel an option on behalf of an address. This will burn the option ERC1155 and withdraw collateral.
/// @dev Requires approval of the option contract
/// This is only doable by an address which wrote an amount of options >= _amount
/// Must be called before expiration
/// @param _from Address on behalf of which the option is cancelled
/// @param _optionId The id of the option to cancel
/// @param _amount Amount to cancel
function cancelOptionFrom(address _from, uint256 _optionId, uint256 _amount) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_cancelOption(_from, _optionId, _amount);
}
/// @notice Cancel an option. This will burn the option ERC1155 and withdraw collateral.
/// @dev This is only doable by an address which wrote an amount of options >= _amount
/// Must be called before expiration
/// @param _optionId The id of the option to cancel
/// @param _amount Amount to cancel
function cancelOption(uint256 _optionId, uint256 _amount) public {
_cancelOption(msg.sender, _optionId, _amount);
}
/// @notice Cancel an option on behalf of an address. This will burn the option ERC1155 and withdraw collateral.
/// @dev This is only doable by an address which wrote an amount of options >= _amount
/// Must be called before expiration
/// @param _from Address on behalf of which the option is cancelled
/// @param _optionId The id of the option to cancel
/// @param _amount Amount to cancel
function _cancelOption(address _from, uint256 _optionId, uint256 _amount) internal nonReentrant {
require(_amount > 0, "Amount <= 0");
require(nbWritten[_from][_optionId] >= _amount, "Not enough written");
burn(_from, _optionId, _amount);
nbWritten[_from][_optionId] = nbWritten[_from][_optionId].sub(_amount);
if (optionData[_optionId].isCall) {
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.sub(_amount);
IERC20(optionData[_optionId].token).safeTransfer(_from, _amount);
} else {
uint256 amount = _amount.mul(optionData[_optionId].strikePrice).div(10**optionData[_optionId].decimals);
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.sub(amount);
denominator.safeTransfer(_from, amount);
}
emit OptionCancelled(_from, _optionId, optionData[_optionId].token, _amount);
}
//////////////////////////////////////////////////
/// @notice Exercise an option on behalf of an address
/// @dev Requires approval of the option contract
/// @param _from Address on behalf of which the option will be exercised
/// @param _optionId The id of the option to exercise
/// @param _amount Amount to exercise
/// @param _referrer Referrer
function exerciseOptionFrom(address _from, uint256 _optionId, uint256 _amount, address _referrer) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_exerciseOption(_from, _optionId, _amount, _referrer);
}
/// @notice Exercise an option
/// @param _optionId The id of the option to exercise
/// @param _amount Amount to exercise
/// @param _referrer Referrer
function exerciseOption(uint256 _optionId, uint256 _amount, address _referrer) public {
_exerciseOption(msg.sender, _optionId, _amount, _referrer);
}
/// @notice Exercise an option on behalf of an address
/// @param _from Address on behalf of which the option will be exercised
/// @param _optionId The id of the option to exercise
/// @param _amount Amount to exercise
/// @param _referrer Referrer
function _exerciseOption(address _from, uint256 _optionId, uint256 _amount, address _referrer) internal nonReentrant {
require(_amount > 0, "Amount <= 0");
OptionData storage data = optionData[_optionId];
burn(_from, _optionId, _amount);
data.exercised = uint256(data.exercised).add(_amount);
// Set referrer or get current if one already exists
_referrer = _trySetReferrer(_from, _referrer);
QuoteExercise memory quote = getExerciseQuote(_from, data, _amount, _referrer, data.decimals);
IERC20(quote.inputToken).safeTransferFrom(_from, address(this), quote.input);
_payFees(_from, IERC20(quote.inputToken), _referrer, quote.fee, quote.feeReferrer, quote.inputDecimals);
if (data.isCall) {
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.sub(quote.output);
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.add(quote.input);
} else {
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.sub(quote.output);
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.add(quote.input);
}
IERC20(quote.outputToken).safeTransfer(_from, quote.output);
emit OptionExercised(_from, _optionId, data.token, _amount);
}
//////////////////////////////////////////////////
/// @notice Withdraw collateral from an option post expiration on behalf of an address.
/// (Funds will be send to the address on behalf of which withdrawal is made)
/// Funds in the option pool will be distributed pro rata of amount of options written by the address
/// Ex : If after expiration date there has been 10 options written and there is 1 eth and 1000 DAI in the pool,
/// Withdraw for each option will be worth 0.1 eth and 100 dai
/// @dev Only callable by addresses which have unclaimed funds for options they wrote
/// Requires approval of the option contract
/// @param _from Address on behalf of which the withdraw call is made (Which will receive the withdrawn funds)
/// @param _optionId The id of the option to withdraw funds from
function withdrawFrom(address _from, uint256 _optionId) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_withdraw(_from, _optionId);
}
/// @notice Withdraw collateral from an option post expiration
/// Funds in the option pool will be distributed pro rata of amount of options written by the address
/// Ex : If after expiration date there has been 10 options written and there is 1 eth and 1000 DAI in the pool,
/// Withdraw for each option will be worth 0.1 eth and 100 dai
/// @dev Only callable by addresses which have unclaimed funds for options they wrote
/// @param _optionId The id of the option to withdraw funds from
function withdraw(uint256 _optionId) public {
_withdraw(msg.sender, _optionId);
}
/// @notice Withdraw collateral from an option post expiration on behalf of an address.
/// (Funds will be send to the address on behalf of which withdrawal is made)
/// Funds in the option pool will be distributed pro rata of amount of options written by the address
/// Ex : If after expiration date there has been 10 options written and there is 1 eth and 1000 DAI in the pool,
/// Withdraw for each option will be worth 0.1 eth and 100 dai
/// @dev Only callable by addresses which have unclaimed funds for options they wrote
/// @param _from Address on behalf of which the withdraw call is made (Which will receive the withdrawn funds)
/// @param _optionId The id of the option to withdraw funds from
function _withdraw(address _from, uint256 _optionId) internal nonReentrant expired(_optionId) {
require(nbWritten[_from][_optionId] > 0, "No option to claim");
OptionData storage data = optionData[_optionId];
uint256 nbTotal = uint256(data.supply).add(data.exercised).sub(data.claimsPreExp);
// Amount of options user still has to claim funds from
uint256 claimsUser = nbWritten[_from][_optionId];
//
uint256 denominatorAmount = pools[_optionId].denominatorAmount.mul(claimsUser).div(nbTotal);
uint256 tokenAmount = pools[_optionId].tokenAmount.mul(claimsUser).div(nbTotal);
//
pools[_optionId].denominatorAmount.sub(denominatorAmount);
pools[_optionId].tokenAmount.sub(tokenAmount);
data.claimsPostExp = uint256(data.claimsPostExp).add(claimsUser);
delete nbWritten[_from][_optionId];
denominator.safeTransfer(_from, denominatorAmount);
IERC20(optionData[_optionId].token).safeTransfer(_from, tokenAmount);
emit Withdraw(_from, _optionId, data.token, claimsUser);
}
//////////////////////////////////////////////////
/// @notice Withdraw collateral from an option pre expiration on behalf of an address.
/// (Funds will be send to the address on behalf of which withdrawal is made)
/// Only opposite side of the collateral will be allocated when withdrawing pre expiration
/// If writer deposited WETH for a WETH/DAI call, he will only receive the strike amount in DAI from a pre-expiration withdrawal,
/// while doing a withdrawal post expiration would make him receive pro rata of funds left in the option pool at the expiration,
/// (Which might be both WETH and DAI if not all options have been exercised)
///
/// @dev Requires approval of the option contract
/// Only callable by addresses which have unclaimed funds for options they wrote
/// This also requires options to have been exercised and not claimed
/// Ex : If a total of 10 options have been written (2 from Alice and 8 from Bob) and 3 options have been exercise :
/// - Alice will be allowed to call withdrawPreExpiration for her 2 options written
/// - Bob will only be allowed to call withdrawPreExpiration for 3 options he wrote
/// - If Alice call first withdrawPreExpiration for her 2 options,
/// there will be only 1 unclaimed exercised options that Bob will be allowed to withdrawPreExpiration
///
/// @param _from Address on behalf of which the withdrawPreExpiration call is made (Which will receive the withdrawn funds)
/// @param _optionId The id of the option to withdraw funds from
/// @param _amount The amount of options for which withdrawPreExpiration
function withdrawPreExpirationFrom(address _from, uint256 _optionId, uint256 _amount) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_withdrawPreExpiration(_from, _optionId, _amount);
}
/// @notice Withdraw collateral from an option pre expiration
/// (Funds will be send to the address on behalf of which withdrawal is made)
/// Only opposite side of the collateral will be allocated when withdrawing pre expiration
/// If writer deposited WETH for a WETH/DAI call, he will only receive the strike amount in DAI from a pre-expiration withdrawal,
/// while doing a withdrawal post expiration would make him receive pro rata of funds left in the option pool at the expiration,
/// (Which might be both WETH and DAI if not all options have been exercised)
///
/// @dev Only callable by addresses which have unclaimed funds for options they wrote
/// This also requires options to have been exercised and not claimed
/// Ex : If a total of 10 options have been written (2 from Alice and 8 from Bob) and 3 options have been exercise :
/// - Alice will be allowed to call withdrawPreExpiration for her 2 options written
/// - Bob will only be allowed to call withdrawPreExpiration for 3 options he wrote
/// - If Alice call first withdrawPreExpiration for her 2 options,
/// there will be only 1 unclaimed exercised options that Bob will be allowed to withdrawPreExpiration
///
/// @param _optionId The id of the option to exercise
/// @param _amount The amount of options for which withdrawPreExpiration
function withdrawPreExpiration(uint256 _optionId, uint256 _amount) public {
_withdrawPreExpiration(msg.sender, _optionId, _amount);
}
/// @notice Withdraw collateral from an option pre expiration on behalf of an address.
/// (Funds will be send to the address on behalf of which withdrawal is made)
/// Only opposite side of the collateral will be allocated when withdrawing pre expiration
/// If writer deposited WETH for a WETH/DAI call, he will only receive the strike amount in DAI from a pre-expiration withdrawal,
/// while doing a withdrawal post expiration would make him receive pro rata of funds left in the option pool at the expiration,
/// (Which might be both WETH and DAI if not all options have been exercised)
///
/// @dev Only callable by addresses which have unclaimed funds for options they wrote
/// This also requires options to have been exercised and not claimed
/// Ex : If a total of 10 options have been written (2 from Alice and 8 from Bob) and 3 options have been exercise :
/// - Alice will be allowed to call withdrawPreExpiration for her 2 options written
/// - Bob will only be allowed to call withdrawPreExpiration for 3 options he wrote
/// - If Alice call first withdrawPreExpiration for her 2 options,
/// there will be only 1 unclaimed exercised options that Bob will be allowed to withdrawPreExpiration
///
/// @param _from Address on behalf of which the withdrawPreExpiration call is made (Which will receive the withdrawn funds)
/// @param _optionId The id of the option to withdraw funds from
/// @param _amount The amount of options for which withdrawPreExpiration
function _withdrawPreExpiration(address _from, uint256 _optionId, uint256 _amount) internal nonReentrant notExpired(_optionId) {
require(_amount > 0, "Amount <= 0");
// Amount of options user still has to claim funds from
uint256 claimsUser = nbWritten[_from][_optionId];
require(claimsUser >= _amount, "Not enough claims");
OptionData storage data = optionData[_optionId];
uint256 nbClaimable = uint256(data.exercised).sub(data.claimsPreExp);
require(nbClaimable >= _amount, "Not enough claimable");
//
nbWritten[_from][_optionId] = nbWritten[_from][_optionId].sub(_amount);
data.claimsPreExp = uint256(data.claimsPreExp).add(_amount);
if (data.isCall) {
uint256 amount = _amount.mul(data.strikePrice).div(10**data.decimals);
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.sub(amount);
denominator.safeTransfer(_from, amount);
} else {
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.sub(_amount);
IERC20(data.token).safeTransfer(_from, _amount);
}
}
//////////////////////////////////////////////////
/// @notice Flash exercise an option on behalf of an address
/// This is usable on options in the money, in order to use a portion of the option collateral
/// to swap a portion of it to the token required to exercise the option and pay protocol fees,
/// and send the profit to the address exercising.
/// This allows any option in the money to be exercised without the need of owning the token needed to exercise
/// @dev Requires approval of the option contract
/// @param _from Address on behalf of which the flash exercise is made (Which will receive the profit)
/// @param _optionId The id of the option to flash exercise
/// @param _amount Amount of option to flash exercise
/// @param _referrer Referrer
/// @param _router The UniswapRouter used to perform the swap (Needs to be a whitelisted router)
/// @param _amountInMax Max amount of collateral token to use for the swap, for the tx to not be reverted
/// @param _path Path used for the routing of the swap
function flashExerciseOptionFrom(address _from, uint256 _optionId, uint256 _amount, address _referrer, IUniswapV2Router02 _router, uint256 _amountInMax, address[] memory _path) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_flashExerciseOption(_from, _optionId, _amount, _referrer, _router, _amountInMax, _path);
}
/// @notice Flash exercise an option
/// This is usable on options in the money, in order to use a portion of the option collateral
/// to swap a portion of it to the token required to exercise the option and pay protocol fees,
/// and send the profit to the address exercising.
/// This allows any option in the money to be exercised without the need of owning the token needed to exercise
/// @param _optionId The id of the option to flash exercise
/// @param _amount Amount of option to flash exercise
/// @param _referrer Referrer
/// @param _router The UniswapRouter used to perform the swap (Needs to be a whitelisted router)
/// @param _amountInMax Max amount of collateral token to use for the swap, for the tx to not be reverted
/// @param _path Path used for the routing of the swap
function flashExerciseOption(uint256 _optionId, uint256 _amount, address _referrer, IUniswapV2Router02 _router, uint256 _amountInMax, address[] memory _path) external {
_flashExerciseOption(msg.sender, _optionId, _amount, _referrer, _router, _amountInMax, _path);
}
/// @notice Flash exercise an option on behalf of an address
/// This is usable on options in the money, in order to use a portion of the option collateral
/// to swap a portion of it to the token required to exercise the option and pay protocol fees,
/// and send the profit to the address exercising.
/// This allows any option in the money to be exercised without the need of owning the token needed to exercise
/// @dev Requires approval of the option contract
/// @param _from Address on behalf of which the flash exercise is made (Which will receive the profit)
/// @param _optionId The id of the option to flash exercise
/// @param _amount Amount of option to flash exercise
/// @param _referrer Referrer
/// @param _router The UniswapRouter used to perform the swap (Needs to be a whitelisted router)
/// @param _amountInMax Max amount of collateral token to use for the swap, for the tx to not be reverted
/// @param _path Path used for the routing of the swap
function _flashExerciseOption(address _from, uint256 _optionId, uint256 _amount, address _referrer, IUniswapV2Router02 _router, uint256 _amountInMax, address[] memory _path) internal nonReentrant {
require(_amount > 0, "Amount <= 0");
burn(_from, _optionId, _amount);
optionData[_optionId].exercised = uint256(optionData[_optionId].exercised).add(_amount);
// Set referrer or get current if one already exists
_referrer = _trySetReferrer(_from, _referrer);
QuoteExercise memory quote = getExerciseQuote(_from, optionData[_optionId], _amount, _referrer, optionData[_optionId].decimals);
IERC20 tokenErc20 = IERC20(optionData[_optionId].token);
uint256 tokenAmountRequired = tokenErc20.balanceOf(address(this));
uint256 denominatorAmountRequired = denominator.balanceOf(address(this));
if (optionData[_optionId].isCall) {
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.sub(quote.output);
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.add(quote.input);
} else {
pools[_optionId].denominatorAmount = pools[_optionId].denominatorAmount.sub(quote.output);
pools[_optionId].tokenAmount = pools[_optionId].tokenAmount.add(quote.input);
}
//
if (quote.output < _amountInMax) {
_amountInMax = quote.output;
}
// Swap enough denominator to tokenErc20 to pay fee + strike price
uint256 tokenAmountUsed = _swap(_router, quote.outputToken, quote.inputToken, quote.input.add(quote.fee).add(quote.feeReferrer), _amountInMax, _path)[0];
// Pay fees
_payFees(address(this), IERC20(quote.inputToken), _referrer, quote.fee, quote.feeReferrer, quote.inputDecimals);
uint256 profit = quote.output.sub(tokenAmountUsed);
// Send profit to sender
IERC20(quote.outputToken).safeTransfer(_from, profit);
//
if (optionData[_optionId].isCall) {
denominatorAmountRequired = denominatorAmountRequired.add(quote.input);
tokenAmountRequired = tokenAmountRequired.sub(quote.output);
} else {
denominatorAmountRequired = denominatorAmountRequired.sub(quote.output);
tokenAmountRequired = tokenAmountRequired.add(quote.input);
}
require(denominator.balanceOf(address(this)) >= denominatorAmountRequired, "Wrong denom bal");
require(tokenErc20.balanceOf(address(this)) >= tokenAmountRequired, "Wrong token bal");
emit OptionExercised(_from, _optionId, optionData[_optionId].token, _amount);
}
//////////////////////////////////////////////////
/// @notice Flash loan collaterals sitting in this contract
/// Loaned amount + fee must be repaid by the end of the transaction for the transaction to not be reverted
/// @param _tokenAddress Token to flashLoan
/// @param _amount Amount to flashLoan
/// @param _receiver Receiver of the flashLoan
function flashLoan(address _tokenAddress, uint256 _amount, IFlashLoanReceiver _receiver) public nonReentrant {
IERC20 _token = IERC20(_tokenAddress);
uint256 startBalance = _token.balanceOf(address(this));
_token.safeTransfer(address(_receiver), _amount);
(uint256 fee,) = feeCalculator.getFeeAmounts(msg.sender, false, _amount, IFeeCalculator.FeeType.FlashLoan);
_receiver.execute(_tokenAddress, _amount, _amount.add(fee));
uint256 endBalance = _token.balanceOf(address(this));
uint256 endBalanceRequired = startBalance.add(fee);
require(endBalance >= endBalanceRequired, "Failed to pay back");
_token.safeTransfer(feeRecipient, endBalance.sub(startBalance));
endBalance = _token.balanceOf(address(this));
require(endBalance >= startBalance, "Failed to pay back");
}
//////////////////////////////////////////////////
//////////////
// Internal //
//////////////
/// @notice Mint ERC1155 representing the option
/// @dev Requires option to not be expired
/// @param _account Address for which ERC1155 is minted
/// @param _amount Amount minted
function mint(address _account, uint256 _id, uint256 _amount) internal notExpired(_id) {
OptionData storage data = optionData[_id];
_mint(_account, _id, _amount, "");
data.supply = uint256(data.supply).add(_amount);
}
/// @notice Burn ERC1155 representing the option
/// @param _account Address from which ERC1155 is burnt
/// @param _amount Amount burnt
function burn(address _account, uint256 _id, uint256 _amount) internal notExpired(_id) {
OptionData storage data = optionData[_id];
data.supply = uint256(data.supply).sub(_amount);
_burn(_account, _id, _amount);
}
/// @notice Utility function to check if a value is inside an array
/// @param _value The value to look for
/// @param _array The array to check
/// @return Whether the value is in the array or not
function _isInArray(address _value, address[] memory _array) internal pure returns(bool) {
uint256 length = _array.length;
for (uint256 i = 0; i < length; ++i) {
if (_array[i] == _value) {
return true;
}
}
return false;
}
/// @notice Pay protocol fees
/// @param _from Address paying protocol fees
/// @param _token The token in which protocol fees are paid
/// @param _referrer The referrer of _from
/// @param _fee Protocol fee to pay to feeRecipient
/// @param _feeReferrer Fee to pay to referrer
/// @param _decimals Token decimals
function _payFees(address _from, IERC20 _token, address _referrer, uint256 _fee, uint256 _feeReferrer, uint8 _decimals) internal {
if (_fee > 0) {
// For flash exercise
if (_from == address(this)) {
_token.safeTransfer(feeRecipient, _fee);
} else {
_token.safeTransferFrom(_from, feeRecipient, _fee);
}
}
if (_feeReferrer > 0) {
// For flash exercise
if (_from == address(this)) {
_token.safeTransfer(_referrer, _feeReferrer);
} else {
_token.safeTransferFrom(_from, _referrer, _feeReferrer);
}
}
// If uPremia rewards are enabled
if (address(uPremia) != address(0)) {
uint256 totalFee = _fee.add(_feeReferrer);
if (totalFee > 0) {
uPremia.mintReward(_from, address(_token), totalFee, _decimals);
}
}
emit FeePaid(_from, address(_token), _referrer, _fee, _feeReferrer);
}
/// @notice Try to set given referrer, returns current referrer if one already exists
/// @param _user Address for which we try to set a referrer
/// @param _referrer Potential referrer
/// @return Actual referrer (Potential referrer, or actual referrer if one already exists)
function _trySetReferrer(address _user, address _referrer) internal returns(address) {
if (address(premiaReferral) != address(0)) {
_referrer = premiaReferral.trySetReferrer(_user, _referrer);
} else {
_referrer = address(0);
}
return _referrer;
}
/// @notice Token swap (Used for flashExercise)
/// @param _router The UniswapRouter contract to use to perform the swap (Must be whitelisted)
/// @param _from Input token for the swap
/// @param _to Output token of the swap
/// @param _amount Amount of output tokens we want
/// @param _amountInMax Max amount of input token to spend for the tx to not revert
/// @param _path Path used for the routing of the swap
/// @return Swap amounts
function _swap(IUniswapV2Router02 _router, address _from, address _to, uint256 _amount, uint256 _amountInMax, address[] memory _path) internal returns (uint256[] memory) {
require(_isInArray(address(_router), whitelistedUniswapRouters), "Router not whitelisted");
IERC20(_from).approve(address(_router), _amountInMax);
uint256[] memory amounts = _router.swapTokensForExactTokens(
_amount,
_amountInMax,
_path,
address(this),
block.timestamp.add(60)
);
IERC20(_from).approve(address(_router), 0);
return amounts;
}
/// @notice Check if option settings are valid (Reverts if not valid)
/// @param _token Token for which option this
/// @param _strikePrice Strike price of the option
/// @param _expiration timestamp of the option
function _preCheckOptionIdCreate(address _token, uint256 _strikePrice, uint256 _expiration) internal view {
require(tokenStrikeIncrement[_token] != 0, "Token not supported");
require(_strikePrice > 0, "Strike <= 0");
require(_strikePrice % tokenStrikeIncrement[_token] == 0, "Wrong strike incr");
require(_expiration > block.timestamp, "Exp passed");
require(_expiration.sub(block.timestamp) <= maxExpiration, "Exp > 1 yr");
require(_expiration % _expirationIncrement == _baseExpiration, "Wrong exp incr");
}
} | Flash exercise an option This is usable on options in the money, in order to use a portion of the option collateral to swap a portion of it to the token required to exercise the option and pay protocol fees, and send the profit to the address exercising. This allows any option in the money to be exercised without the need of owning the token needed to exercise _optionId The id of the option to flash exercise _amount Amount of option to flash exercise _referrer Referrer _router The UniswapRouter used to perform the swap (Needs to be a whitelisted router) _amountInMax Max amount of collateral token to use for the swap, for the tx to not be reverted _path Path used for the routing of the swap | function flashExerciseOption(uint256 _optionId, uint256 _amount, address _referrer, IUniswapV2Router02 _router, uint256 _amountInMax, address[] memory _path) external {
_flashExerciseOption(msg.sender, _optionId, _amount, _referrer, _router, _amountInMax, _path);
}
| 13,115,115 |
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
// SPDX-License-Identifier: GPL-3.0-or-later
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File interfaces/IStrategy.sol
pragma solidity 0.8.9;
interface IStrategy {
function name() external view returns (string memory);
function deposit() external payable returns (bool);
function balance() external view returns (uint256);
function withdraw(uint256 amount) external returns (bool);
function withdrawAll() external returns (uint256);
function harvestable() external view returns (uint256);
function harvest() external returns (uint256);
function strategist() external view returns (address);
function shutdown() external returns (bool);
function hasPendingFunds() external view returns (bool);
}
// File interfaces/IPreparable.sol
pragma solidity 0.8.9;
interface IPreparable {
event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay);
event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay);
event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue);
event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event ConfigReset(bytes32 indexed key);
}
// File interfaces/IVault.sol
pragma solidity 0.8.9;
/**
* @title Interface for a Vault
*/
interface IVault is IPreparable {
event StrategyActivated(address indexed strategy);
event StrategyDeactivated(address indexed strategy);
/**
* @dev 'netProfit' is the profit after all fees have been deducted
*/
event Harvest(uint256 indexed netProfit, uint256 indexed loss);
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external;
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external returns (bool);
function initializeStrategy(address strategy_) external returns (bool);
function withdrawAll() external;
function withdrawFromReserve(uint256 amount) external;
function getStrategy() external view returns (IStrategy);
function getStrategiesWaitingForRemoval() external view returns (address[] memory);
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256);
function getTotalUnderlying() external view returns (uint256);
function getUnderlying() external view returns (address);
}
// File interfaces/IVaultReserve.sol
pragma solidity 0.8.9;
interface IVaultReserve {
event Deposit(address indexed vault, address indexed token, uint256 amount);
event Withdraw(address indexed vault, address indexed token, uint256 amount);
event VaultListed(address indexed vault);
function deposit(address token, uint256 amount) external payable returns (bool);
function withdraw(address token, uint256 amount) external returns (bool);
function getBalance(address vault, address token) external view returns (uint256);
function canWithdraw(address vault) external view returns (bool);
}
// File interfaces/pool/ILiquidityPool.sol
pragma solidity 0.8.9;
interface ILiquidityPool is IPreparable {
event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens);
event DepositFor(
address indexed minter,
address indexed mintee,
uint256 depositAmount,
uint256 mintedLpTokens
);
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
event LpTokenSet(address indexed lpToken);
event StakerVaultSet(address indexed stakerVault);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256);
function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256);
function deposit(uint256 mintAmount) external payable returns (uint256);
function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256);
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
returns (uint256);
function depositFor(address account, uint256 depositAmount) external payable returns (uint256);
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) external payable returns (uint256);
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
returns (uint256);
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external;
function executeNewVault() external returns (address);
function executeNewMaxWithdrawalFee() external returns (uint256);
function executeNewRequiredReserves() external returns (uint256);
function executeNewReserveDeviation() external returns (uint256);
function setLpToken(address _lpToken) external returns (bool);
function setStaker() external returns (bool);
function isCapped() external returns (bool);
function uncap() external returns (bool);
function updateDepositCap(uint256 _depositCap) external returns (bool);
function getUnderlying() external view returns (address);
function getLpToken() external view returns (address);
function getWithdrawalFee(address account, uint256 amount) external view returns (uint256);
function getVault() external view returns (IVault);
function exchangeRate() external view returns (uint256);
}
// File interfaces/IGasBank.sol
pragma solidity 0.8.9;
interface IGasBank {
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, address indexed receiver, uint256 value);
function depositFor(address account) external payable;
function withdrawUnused(address account) external;
function withdrawFrom(address account, uint256 amount) external;
function withdrawFrom(
address account,
address payable to,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/oracles/IOracleProvider.sol
pragma solidity 0.8.9;
interface IOracleProvider {
/// @notice Quotes the USD price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the USD price of the asset
function getPriceUSD(address baseAsset) external view returns (uint256);
/// @notice Quotes the ETH price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the ETH price of the asset
function getPriceETH(address baseAsset) external view returns (uint256);
}
// File libraries/AddressProviderMeta.sol
pragma solidity 0.8.9;
library AddressProviderMeta {
struct Meta {
bool freezable;
bool frozen;
}
function fromUInt(uint256 value) internal pure returns (Meta memory) {
Meta memory meta;
meta.freezable = (value & 1) == 1;
meta.frozen = ((value >> 1) & 1) == 1;
return meta;
}
function toUInt(Meta memory meta) internal pure returns (uint256) {
uint256 value;
value |= meta.freezable ? 1 : 0;
value |= meta.frozen ? 1 << 1 : 0;
return value;
}
}
// File interfaces/IAddressProvider.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IAddressProvider is IPreparable {
event KnownAddressKeyAdded(bytes32 indexed key);
event StakerVaultListed(address indexed stakerVault);
event StakerVaultDelisted(address indexed stakerVault);
event ActionListed(address indexed action);
event PoolListed(address indexed pool);
event PoolDelisted(address indexed pool);
event VaultUpdated(address indexed previousVault, address indexed newVault);
/** Key functions */
function getKnownAddressKeys() external view returns (bytes32[] memory);
function freezeAddress(bytes32 key) external;
/** Pool functions */
function allPools() external view returns (address[] memory);
function addPool(address pool) external;
function poolsCount() external view returns (uint256);
function getPoolAtIndex(uint256 index) external view returns (address);
function isPool(address pool) external view returns (bool);
function removePool(address pool) external returns (bool);
function getPoolForToken(address token) external view returns (ILiquidityPool);
function safeGetPoolForToken(address token) external view returns (address);
/** Vault functions */
function updateVault(address previousVault, address newVault) external;
function allVaults() external view returns (address[] memory);
function vaultsCount() external view returns (uint256);
function getVaultAtIndex(uint256 index) external view returns (address);
function isVault(address vault) external view returns (bool);
/** Action functions */
function allActions() external view returns (address[] memory);
function addAction(address action) external returns (bool);
function isAction(address action) external view returns (bool);
/** Address functions */
function initializeAddress(
bytes32 key,
address initialAddress,
bool frezable
) external;
function initializeAndFreezeAddress(bytes32 key, address initialAddress) external;
function getAddress(bytes32 key) external view returns (address);
function getAddress(bytes32 key, bool checkExists) external view returns (address);
function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory);
function prepareAddress(bytes32 key, address newAddress) external returns (bool);
function executeAddress(bytes32 key) external returns (address);
function resetAddress(bytes32 key) external returns (bool);
/** Staker vault functions */
function allStakerVaults() external view returns (address[] memory);
function tryGetStakerVault(address token) external view returns (bool, address);
function getStakerVault(address token) external view returns (address);
function addStakerVault(address stakerVault) external returns (bool);
function isStakerVault(address stakerVault, address token) external view returns (bool);
function isStakerVaultRegistered(address stakerVault) external view returns (bool);
function isWhiteListedFeeHandler(address feeHandler) external view returns (bool);
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity 0.8.9;
interface IInflationManager {
event KeeperGaugeListed(address indexed pool, address indexed keeperGauge);
event AmmGaugeListed(address indexed token, address indexed ammGauge);
event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge);
event AmmGaugeDelisted(address indexed token, address indexed ammGauge);
/** Pool functions */
function setKeeperGauge(address pool, address _keeperGauge) external returns (bool);
function setAmmGauge(address token, address _ammGauge) external returns (bool);
function getAllAmmGauges() external view returns (address[] memory);
function getLpRateForStakerVault(address stakerVault) external view returns (uint256);
function getKeeperRateForPool(address pool) external view returns (uint256);
function getAmmRateForToken(address token) external view returns (uint256);
function getKeeperWeightForPool(address pool) external view returns (uint256);
function getAmmWeightForToken(address pool) external view returns (uint256);
function getLpPoolWeight(address pool) external view returns (uint256);
function getKeeperGaugeForPool(address pool) external view returns (address);
function getAmmGaugeForToken(address token) external view returns (address);
function isInflationWeightManager(address account) external view returns (bool);
function removeStakerVaultFromInflation(address stakerVault, address lpToken) external;
function addGaugeForVault(address lpToken) external returns (bool);
function whitelistGauge(address gauge) external;
function checkpointAllGauges() external returns (bool);
function mintRewards(address beneficiary, uint256 amount) external;
function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool)
external
returns (bool);
/** Weight setter functions **/
function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool);
function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool);
function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool);
function executeLpPoolWeight(address lpToken) external returns (uint256);
function executeAmmTokenWeight(address token) external returns (uint256);
function executeKeeperPoolWeight(address pool) external returns (uint256);
function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights)
external
returns (bool);
function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool);
function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool);
function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool);
}
// File interfaces/IController.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IController is IPreparable {
function addressProvider() external view returns (IAddressProvider);
function inflationManager() external view returns (IInflationManager);
function addStakerVault(address stakerVault) external returns (bool);
function removePool(address pool) external returns (bool);
/** Keeper functions */
function prepareKeeperRequiredStakedBKD(uint256 amount) external;
function executeKeeperRequiredStakedBKD() external;
function getKeeperRequiredStakedBKD() external view returns (uint256);
function canKeeperExecuteAction(address keeper) external view returns (bool);
/** Miscellaneous functions */
function getTotalEthRequiredForGas(address payer) external view returns (uint256);
}
// File libraries/ScaledMath.sol
pragma solidity 0.8.9;
/*
* @dev To use functions of this contract, at least one of the numbers must
* be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE`
* if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale
* of the number not scaled by `DECIMAL_SCALE`
*/
library ScaledMath {
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant DECIMAL_SCALE = 1e18;
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant ONE = 1e18;
/**
* @notice Performs a multiplication between two scaled numbers
*/
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / DECIMAL_SCALE;
}
/**
* @notice Performs a division between two scaled numbers
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE) / b;
}
/**
* @notice Performs a division between two numbers, rounding up the result
*/
function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE + b - 1) / b;
}
/**
* @notice Performs a division between two numbers, ignoring any scaling and rounding up the result
*/
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
}
// File libraries/Errors.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Error {
string internal constant ADDRESS_WHITELISTED = "address already whitelisted";
string internal constant ADMIN_ALREADY_SET = "admin has already been set once";
string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted";
string internal constant ADDRESS_NOT_FOUND = "address not found";
string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
string internal constant CONTRACT_PAUSED = "contract is paused";
string internal constant INVALID_AMOUNT = "invalid amount";
string internal constant INVALID_INDEX = "invalid index";
string internal constant INVALID_VALUE = "invalid msg.value";
string internal constant INVALID_SENDER = "invalid msg.sender";
string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
string internal constant INVALID_DECIMALS = "incorrect number of decimals";
string internal constant INVALID_ARGUMENT = "invalid argument";
string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
string internal constant INVALID_POOL_IMPLEMENTATION =
"invalid pool implementation for given coin";
string internal constant INVALID_LP_TOKEN_IMPLEMENTATION =
"invalid LP Token implementation for given coin";
string internal constant INVALID_VAULT_IMPLEMENTATION =
"invalid vault implementation for given coin";
string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION =
"invalid stakerVault implementation for given coin";
string internal constant INSUFFICIENT_BALANCE = "insufficient balance";
string internal constant ADDRESS_ALREADY_SET = "Address is already set";
string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance";
string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received";
string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist";
string internal constant ADDRESS_FROZEN = "address is frozen";
string internal constant ROLE_EXISTS = "role already exists";
string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role";
string internal constant UNAUTHORIZED_ACCESS = "unauthorized access";
string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed";
string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed";
string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed";
string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed";
string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold";
string internal constant NO_POSITION_EXISTS = "no position exists";
string internal constant POSITION_ALREADY_EXISTS = "position already exists";
string internal constant PROTOCOL_NOT_FOUND = "protocol not found";
string internal constant TOP_UP_FAILED = "top up failed";
string internal constant SWAP_PATH_NOT_FOUND = "swap path not found";
string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported";
string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN =
"not enough funds were withdrawn from the pool";
string internal constant FAILED_TRANSFER = "transfer failed";
string internal constant FAILED_MINT = "mint failed";
string internal constant FAILED_REPAY_BORROW = "repay borrow failed";
string internal constant FAILED_METHOD_CALL = "method call failed";
string internal constant NOTHING_TO_CLAIM = "there is no claimable balance";
string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
string internal constant INVALID_MINTER =
"the minter address of the LP token and the pool address do not match";
string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
string internal constant DEADLINE_NOT_ZERO = "deadline must be 0";
string internal constant DEADLINE_NOT_SET = "deadline is 0";
string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
string internal constant DELAY_TOO_SHORT = "delay be at least 3 days";
string internal constant INSUFFICIENT_UPDATE_BALANCE =
"insufficient funds for updating the position";
string internal constant SAME_AS_CURRENT = "value must be different to existing value";
string internal constant NOT_CAPPED = "the pool is not currently capped";
string internal constant ALREADY_CAPPED = "the pool is already capped";
string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap";
string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas";
string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw";
string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
string internal constant DEPOSIT_FAILED = "deposit failed";
string internal constant GAS_TOO_HIGH = "too much ETH used for gas";
string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add";
string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed";
string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet";
string internal constant UNDERLYING_NOT_WITHDRAWABLE =
"pool does not support additional underlying coins to be withdrawn";
string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down";
string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist";
string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported";
string internal constant NO_DEX_SET = "no dex has been set for token";
string internal constant INVALID_TOKEN_PAIR = "invalid token pair";
string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
string internal constant ADDRESS_NOT_ACTION = "address is not registered action";
string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance";
string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
string internal constant GAUGE_EXISTS = "Gauge already exists";
string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist";
string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
string internal constant PREPARED_WITHDRAWAL =
"Cannot relock funds when withdrawal is being prepared";
string internal constant ASSET_NOT_SUPPORTED = "Asset not supported";
string internal constant STALE_PRICE = "Price is stale";
string internal constant NEGATIVE_PRICE = "Price is negative";
string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked";
string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded";
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// 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;
}
}
// File libraries/EnumerableMapping.sol
pragma solidity 0.8.9;
library EnumerableMapping {
using EnumerableSet for EnumerableSet.Bytes32Set;
// Code take from contracts/utils/structs/EnumerableMap.sol
// because the helper functions are private
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
// AddressToAddressMap
struct AddressToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToAddressMap storage map,
address key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToAddressMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToAddressMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToAddressMap storage map, uint256 index)
internal
view
returns (address, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToAddressMap storage map, address key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToAddressMap storage map, address key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(uint256(uint160(key)))))));
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index)
internal
view
returns (address, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToUintMap storage map, address key)
internal
view
returns (bool, uint256)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key)))));
}
// Bytes32ToUIntMap
struct Bytes32ToUIntMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
Bytes32ToUIntMap storage map,
bytes32 key,
uint256 value
) internal returns (bool) {
return _set(map._inner, key, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToUIntMap storage map, bytes32 key) internal returns (bool) {
return _remove(map._inner, key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool) {
return _contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(Bytes32ToUIntMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToUIntMap storage map, uint256 index)
internal
view
returns (bytes32, uint256)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (key, uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(Bytes32ToUIntMap storage map, bytes32 key)
internal
view
returns (bool, uint256)
{
(bool success, bytes32 value) = _tryGet(map._inner, key);
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (uint256) {
return uint256(_get(map._inner, key));
}
}
// File libraries/EnumerableExtensions.sol
pragma solidity 0.8.9;
library EnumerableExtensions {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
using EnumerableMapping for EnumerableMapping.AddressToAddressMap;
using EnumerableMapping for EnumerableMapping.AddressToUintMap;
using EnumerableMapping for EnumerableMapping.Bytes32ToUIntMap;
function toArray(EnumerableSet.AddressSet storage addresses)
internal
view
returns (address[] memory)
{
uint256 len = addresses.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = addresses.at(i);
}
return result;
}
function toArray(EnumerableSet.Bytes32Set storage values)
internal
view
returns (bytes32[] memory)
{
uint256 len = values.length();
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = values.at(i);
}
return result;
}
function keyAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index)
internal
view
returns (address)
{
(address key, ) = map.at(index);
return key;
}
function valueAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index)
internal
view
returns (address)
{
(, address value) = map.at(index);
return value;
}
function keyAt(EnumerableMapping.AddressToUintMap storage map, uint256 index)
internal
view
returns (address)
{
(address key, ) = map.at(index);
return key;
}
function keyAt(EnumerableMapping.Bytes32ToUIntMap storage map, uint256 index)
internal
view
returns (bytes32)
{
(bytes32 key, ) = map.at(index);
return key;
}
function valueAt(EnumerableMapping.AddressToUintMap storage map, uint256 index)
internal
view
returns (uint256)
{
(, uint256 value) = map.at(index);
return value;
}
function keysArray(EnumerableMapping.AddressToAddressMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
function valuesArray(EnumerableMapping.AddressToAddressMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = valueAt(map, i);
}
return result;
}
function keysArray(EnumerableMapping.AddressToUintMap storage map)
internal
view
returns (address[] memory)
{
uint256 len = map.length();
address[] memory result = new address[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
function keysArray(EnumerableMapping.Bytes32ToUIntMap storage map)
internal
view
returns (bytes32[] memory)
{
uint256 len = map.length();
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; i++) {
result[i] = keyAt(map, i);
}
return result;
}
}
// File interfaces/IRoleManager.sol
pragma solidity 0.8.9;
interface IRoleManager {
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
address account
) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
bytes32 role3,
address account
) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
}
// File interfaces/tokenomics/IBkdToken.sol
pragma solidity 0.8.9;
interface IBkdToken is IERC20 {
function mint(address account, uint256 amount) external;
}
// File libraries/AddressProviderKeys.sol
pragma solidity 0.8.9;
library AddressProviderKeys {
bytes32 internal constant _TREASURY_KEY = "treasury";
bytes32 internal constant _GAS_BANK_KEY = "gasBank";
bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve";
bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry";
bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider";
bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory";
bytes32 internal constant _CONTROLLER_KEY = "controller";
bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker";
bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager";
}
// File libraries/AddressProviderHelpers.sol
pragma solidity 0.8.9;
library AddressProviderHelpers {
/**
* @return The address of the treasury.
*/
function getTreasury(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._TREASURY_KEY);
}
/**
* @return The gas bank.
*/
function getGasBank(IAddressProvider provider) internal view returns (IGasBank) {
return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY));
}
/**
* @return The address of the vault reserve.
*/
function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) {
return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY));
}
/**
* @return The address of the swapperRegistry.
*/
function getSwapperRegistry(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY);
}
/**
* @return The oracleProvider.
*/
function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) {
return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY));
}
/**
* @return the address of the BKD locker
*/
function getBKDLocker(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY);
}
/**
* @return the address of the BKD locker
*/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) {
return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY));
}
/**
* @return the controller
*/
function getController(IAddressProvider provider) internal view returns (IController) {
return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY));
}
}
// File contracts/vault/VaultStorage.sol
pragma solidity 0.8.9;
contract VaultStorage {
uint256 public currentAllocated;
uint256 public waitingForRemovalAllocated;
address public pool;
uint256 public totalDebt;
bool public strategyActive;
EnumerableMapping.AddressToUintMap internal _strategiesWaitingForRemoval;
}
contract VaultStorageV1 is VaultStorage {
/**
* @dev This is to avoid breaking contracts inheriting from `VaultStorage`
* such as `Erc20Vault`, especially if they have storage variables
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
* for more details
*
* A new field can be added using a new contract such as
*
* ```solidity
* contract VaultStorageV2 is VaultStorage {
* uint256 someNewField;
* uint256[49] private __gap;
* }
*/
uint256[50] private __gap;
}
// File contracts/utils/Preparable.sol
pragma solidity 0.8.9;
/**
* @notice Implements the base logic for a two-phase commit
* @dev This does not implements any access-control so publicly exposed
* callers should make sure to have the proper checks in palce
*/
contract Preparable is IPreparable {
uint256 private constant _MIN_DELAY = 3 days;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingUInts256;
mapping(bytes32 => address) public currentAddresses;
mapping(bytes32 => uint256) public currentUInts256;
/**
* @dev Deadlines shares the same namespace regardless of the type
* of the pending variable so this needs to be enforced in the caller
*/
mapping(bytes32 => uint256) public deadlines;
function _prepareDeadline(bytes32 key, uint256 delay) internal {
require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO);
require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT);
deadlines[key] = block.timestamp + delay;
}
/**
* @notice Prepares an uint256 that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
uint256 value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingUInts256[key] = value;
emit ConfigPreparedNumber(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, uint256 value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Prepares an address that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
address value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingAddresses[key] = value;
emit ConfigPreparedAddress(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, address value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Reset a uint256 key
* @return `true` if success.
*/
function _resetUInt256Config(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingUInts256[key] = 0;
emit ConfigReset(key);
return true;
}
/**
* @notice Reset an address key
* @return `true` if success.
*/
function _resetAddressConfig(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingAddresses[key] = address(0);
emit ConfigReset(key);
return true;
}
/**
* @dev Checks the deadline of the key and reset it
*/
function _executeDeadline(bytes32 key) internal {
uint256 deadline = deadlines[key];
require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED);
require(deadline != 0, Error.DEADLINE_NOT_SET);
deadlines[key] = 0;
}
/**
* @notice Execute uint256 config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeUInt256(bytes32 key) internal returns (uint256) {
_executeDeadline(key);
uint256 newValue = pendingUInts256[key];
_setConfig(key, newValue);
return newValue;
}
/**
* @notice Execute address config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeAddress(bytes32 key) internal returns (address) {
_executeDeadline(key);
address newValue = pendingAddresses[key];
_setConfig(key, newValue);
return newValue;
}
function _setConfig(bytes32 key, address value) internal returns (address) {
address oldValue = currentAddresses[key];
currentAddresses[key] = value;
pendingAddresses[key] = address(0);
deadlines[key] = 0;
emit ConfigUpdatedAddress(key, oldValue, value);
return value;
}
function _setConfig(bytes32 key, uint256 value) internal returns (uint256) {
uint256 oldValue = currentUInts256[key];
currentUInts256[key] = value;
pendingUInts256[key] = 0;
deadlines[key] = 0;
emit ConfigUpdatedNumber(key, oldValue, value);
return value;
}
}
// File contracts/utils/IPausable.sol
pragma solidity 0.8.9;
interface IPausable {
function pause() external returns (bool);
function unpause() external returns (bool);
function isPaused() external view returns (bool);
function isAuthorizedToPause(address account) external view returns (bool);
}
// File libraries/Roles.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Roles {
bytes32 internal constant GOVERNANCE = "governance";
bytes32 internal constant ADDRESS_PROVIDER = "address_provider";
bytes32 internal constant POOL_FACTORY = "pool_factory";
bytes32 internal constant CONTROLLER = "controller";
bytes32 internal constant GAUGE_ZAP = "gauge_zap";
bytes32 internal constant MAINTENANCE = "maintenance";
bytes32 internal constant INFLATION_MANAGER = "inflation_manager";
bytes32 internal constant POOL = "pool";
bytes32 internal constant VAULT = "vault";
}
// File contracts/access/AuthorizationBase.sol
pragma solidity 0.8.9;
/**
* @notice Provides modifiers for authorization
*/
abstract contract AuthorizationBase {
/**
* @notice Only allows a sender with `role` to perform the given action
*/
modifier onlyRole(bytes32 role) {
require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with GOVERNANCE role to perform the given action
*/
modifier onlyGovernance() {
require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles2(bytes32 role1, bytes32 role2) {
require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles3(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_roleManager().hasAnyRole(role1, role2, role3, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
function roleManager() external view virtual returns (IRoleManager) {
return _roleManager();
}
function _roleManager() internal view virtual returns (IRoleManager);
}
// File contracts/access/Authorization.sol
pragma solidity 0.8.9;
contract Authorization is AuthorizationBase {
IRoleManager internal immutable __roleManager;
constructor(IRoleManager roleManager) {
__roleManager = roleManager;
}
function _roleManager() internal view override returns (IRoleManager) {
return __roleManager;
}
}
// File contracts/vault/Vault.sol
pragma solidity 0.8.9;
abstract contract Vault is IVault, Authorization, VaultStorageV1, Preparable, Initializable {
using ScaledMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableExtensions for EnumerableSet.AddressSet;
using EnumerableMapping for EnumerableMapping.AddressToUintMap;
using EnumerableExtensions for EnumerableMapping.AddressToUintMap;
using AddressProviderHelpers for IAddressProvider;
bytes32 internal constant _STRATEGY_KEY = "Strategy";
bytes32 internal constant _PERFORMANCE_FEE_KEY = "PerformanceFee";
bytes32 internal constant _STRATEGIST_FEE_KEY = "StrategistFee";
bytes32 internal constant _DEBT_LIMIT_KEY = "DebtLimit";
bytes32 internal constant _TARGET_ALLOCATION_KEY = "TargetAllocation";
bytes32 internal constant _RESERVE_FEE_KEY = "ReserveFee";
bytes32 internal constant _BOUND_KEY = "Bound";
uint256 internal constant _INITIAL_RESERVE_FEE = 0.01e18;
uint256 internal constant _INITIAL_STRATEGIST_FEE = 0.1e18;
uint256 internal constant _INITIAL_PERFORMANCE_FEE = 0;
uint256 public constant MAX_PERFORMANCE_FEE = 0.5e18;
uint256 public constant MAX_DEVIATION_BOUND = 0.5e18;
uint256 public constant STRATEGY_DELAY = 5 days;
IController public immutable controller;
IAddressProvider public immutable addressProvider;
IVaultReserve public immutable reserve;
modifier onlyPool() {
require(msg.sender == pool, Error.UNAUTHORIZED_ACCESS);
_;
}
modifier onlyPoolOrGovernance() {
require(
msg.sender == pool || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
modifier onlyPoolOrMaintenance() {
require(
msg.sender == pool || _roleManager().hasRole(Roles.MAINTENANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
constructor(IController _controller)
Authorization(_controller.addressProvider().getRoleManager())
{
controller = _controller;
IAddressProvider addressProvider_ = _controller.addressProvider();
addressProvider = addressProvider_;
reserve = IVaultReserve(addressProvider_.getVaultReserve());
}
function _initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) internal {
require(_debtLimit <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(_targetAllocation <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(_bound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT);
pool = _pool;
_setConfig(_DEBT_LIMIT_KEY, _debtLimit);
_setConfig(_TARGET_ALLOCATION_KEY, _targetAllocation);
_setConfig(_BOUND_KEY, _bound);
_setConfig(_RESERVE_FEE_KEY, _INITIAL_RESERVE_FEE);
_setConfig(_STRATEGIST_FEE_KEY, _INITIAL_STRATEGIST_FEE);
_setConfig(_PERFORMANCE_FEE_KEY, _INITIAL_PERFORMANCE_FEE);
}
/**
* @notice Handles deposits from the liquidity pool
*/
function deposit() external payable override onlyPoolOrMaintenance {
// solhint-disable-previous-line ordering
_deposit();
}
/**
* @notice Withdraws specified amount of underlying from vault.
* @dev If the specified amount exceeds idle funds, an amount of funds is withdrawn
* from the strategy such that it will achieve a target allocation for after the
* amount has been withdrawn.
* @param amount Amount to withdraw.
* @return `true` if successful.
*/
function withdraw(uint256 amount) external override onlyPoolOrGovernance returns (bool) {
IStrategy strategy = getStrategy();
uint256 availableUnderlying_ = _availableUnderlying();
if (availableUnderlying_ < amount) {
if (address(strategy) == address(0)) return false;
uint256 allocated = strategy.balance();
uint256 requiredWithdrawal = amount - availableUnderlying_;
if (requiredWithdrawal > allocated) return false;
// compute withdrawal amount to sustain target allocation
uint256 newTarget = (allocated - requiredWithdrawal).scaledMul(getTargetAllocation());
uint256 excessAmount = allocated - newTarget;
strategy.withdraw(excessAmount);
currentAllocated = _computeNewAllocated(currentAllocated, excessAmount);
} else {
uint256 allocatedUnderlying = 0;
if (address(strategy) != address(0))
allocatedUnderlying = IStrategy(strategy).balance();
uint256 totalUnderlying = availableUnderlying_ +
allocatedUnderlying +
waitingForRemovalAllocated;
uint256 totalUnderlyingAfterWithdraw = totalUnderlying - amount;
_rebalance(totalUnderlyingAfterWithdraw, allocatedUnderlying);
}
_transfer(pool, amount);
return true;
}
/**
* @notice Withdraws all funds from vault and strategy and transfer them to the pool.
*/
function withdrawAll() external override onlyPoolOrGovernance {
_withdrawAllFromStrategy();
_transfer(pool, _availableUnderlying());
}
/**
* @notice Withdraws specified amount of underlying from reserve to vault.
* @dev Withdraws from reserve will cause a spike in pool exchange rate.
* Pool deposits should be paused during this to prevent front running
* @param amount Amount to withdraw.
*/
function withdrawFromReserve(uint256 amount) external override onlyGovernance {
require(amount > 0, Error.INVALID_AMOUNT);
require(IPausable(pool).isPaused(), Error.POOL_NOT_PAUSED);
uint256 reserveBalance_ = reserve.getBalance(address(this), getUnderlying());
require(amount <= reserveBalance_, Error.INSUFFICIENT_BALANCE);
reserve.withdraw(getUnderlying(), amount);
}
/**
* @notice Activate the current strategy set for the vault.
* @return `true` if strategy has been activated
*/
function activateStrategy() external onlyGovernance returns (bool) {
return _activateStrategy();
}
/**
* @notice Deactivates a strategy.
* @return `true` if strategy has been deactivated
*/
function deactivateStrategy() external onlyGovernance returns (bool) {
return _deactivateStrategy();
}
/**
* @notice Initializes the vault's strategy.
* @dev Bypasses the time delay, but can only be called if strategy is not set already.
* @param strategy_ Address of the strategy.
* @return `true` if successful.
*/
function initializeStrategy(address strategy_) external override onlyGovernance returns (bool) {
require(currentAddresses[_STRATEGY_KEY] == address(0), Error.ADDRESS_ALREADY_SET);
require(strategy_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
_setConfig(_STRATEGY_KEY, strategy_);
_activateStrategy();
require(IStrategy(strategy_).strategist() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
return true;
}
/**
* @notice Prepare update of the vault's strategy (with time delay enforced).
* @param newStrategy Address of the new strategy.
* @return `true` if successful.
*/
function prepareNewStrategy(address newStrategy) external onlyGovernance returns (bool) {
return _prepare(_STRATEGY_KEY, newStrategy, STRATEGY_DELAY);
}
/**
* @notice Execute strategy update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New strategy address.
*/
function executeNewStrategy() external returns (address) {
_executeDeadline(_STRATEGY_KEY);
IStrategy strategy = getStrategy();
if (address(strategy) != address(0)) {
_harvest();
strategy.shutdown();
strategy.withdrawAll();
// there might still be some balance left if the strategy did not
// manage to withdraw all funds (e.g. due to locking)
uint256 remainingStrategyBalance = strategy.balance();
if (remainingStrategyBalance > 0) {
_strategiesWaitingForRemoval.set(address(strategy), remainingStrategyBalance);
waitingForRemovalAllocated += remainingStrategyBalance;
}
}
_deactivateStrategy();
currentAllocated = 0;
totalDebt = 0;
address newStrategy = pendingAddresses[_STRATEGY_KEY];
_setConfig(_STRATEGY_KEY, newStrategy);
if (newStrategy != address(0)) {
_activateStrategy();
}
return newStrategy;
}
function resetNewStrategy() external onlyGovernance returns (bool) {
return _resetAddressConfig(_STRATEGY_KEY);
}
/**
* @notice Prepare update of performance fee (with time delay enforced).
* @param newPerformanceFee New performance fee value.
* @return `true` if successful.
*/
function preparePerformanceFee(uint256 newPerformanceFee)
external
onlyGovernance
returns (bool)
{
require(newPerformanceFee <= MAX_PERFORMANCE_FEE, Error.INVALID_AMOUNT);
return _prepare(_PERFORMANCE_FEE_KEY, newPerformanceFee);
}
/**
* @notice Execute update of performance fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New performance fee.
*/
function executePerformanceFee() external returns (uint256) {
return _executeUInt256(_PERFORMANCE_FEE_KEY);
}
function resetPerformanceFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_PERFORMANCE_FEE_KEY);
}
/**
* @notice Prepare update of strategist fee (with time delay enforced).
* @param newStrategistFee New strategist fee value.
* @return `true` if successful.
*/
function prepareStrategistFee(uint256 newStrategistFee) external onlyGovernance returns (bool) {
_checkFeesInvariant(getReserveFee(), newStrategistFee);
return _prepare(_STRATEGIST_FEE_KEY, newStrategistFee);
}
/**
* @notice Execute update of strategist fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New strategist fee.
*/
function executeStrategistFee() external returns (uint256) {
uint256 newStrategistFee = _executeUInt256(_STRATEGIST_FEE_KEY);
_checkFeesInvariant(getReserveFee(), newStrategistFee);
return newStrategistFee;
}
function resetStrategistFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_STRATEGIST_FEE_KEY);
}
/**
* @notice Prepare update of debt limit (with time delay enforced).
* @param newDebtLimit New debt limit.
* @return `true` if successful.
*/
function prepareDebtLimit(uint256 newDebtLimit) external onlyGovernance returns (bool) {
return _prepare(_DEBT_LIMIT_KEY, newDebtLimit);
}
/**
* @notice Execute update of debt limit (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New debt limit.
*/
function executeDebtLimit() external returns (uint256) {
uint256 debtLimit = _executeUInt256(_DEBT_LIMIT_KEY);
uint256 debtLimitAllocated = currentAllocated.scaledMul(debtLimit);
if (totalDebt >= debtLimitAllocated) {
_handleExcessDebt();
}
return debtLimit;
}
function resetDebtLimit() external onlyGovernance returns (bool) {
return _resetUInt256Config(_DEBT_LIMIT_KEY);
}
/**
* @notice Prepare update of target allocation (with time delay enforced).
* @param newTargetAllocation New target allocation.
* @return `true` if successful.
*/
function prepareTargetAllocation(uint256 newTargetAllocation)
external
onlyGovernance
returns (bool)
{
return _prepare(_TARGET_ALLOCATION_KEY, newTargetAllocation);
}
/**
* @notice Execute update of target allocation (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New target allocation.
*/
function executeTargetAllocation() external returns (uint256) {
uint256 targetAllocation = _executeUInt256(_TARGET_ALLOCATION_KEY);
_deposit();
return targetAllocation;
}
function resetTargetAllocation() external onlyGovernance returns (bool) {
return _resetUInt256Config(_TARGET_ALLOCATION_KEY);
}
/**
* @notice Prepare update of reserve fee (with time delay enforced).
* @param newReserveFee New reserve fee.
* @return `true` if successful.
*/
function prepareReserveFee(uint256 newReserveFee) external onlyGovernance returns (bool) {
_checkFeesInvariant(newReserveFee, getStrategistFee());
return _prepare(_RESERVE_FEE_KEY, newReserveFee);
}
/**
* @notice Execute update of reserve fee (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New reserve fee.
*/
function executeReserveFee() external returns (uint256) {
uint256 newReserveFee = _executeUInt256(_RESERVE_FEE_KEY);
_checkFeesInvariant(newReserveFee, getStrategistFee());
return newReserveFee;
}
function resetReserveFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_RESERVE_FEE_KEY);
}
/**
* @notice Prepare update of deviation bound for strategy allocation (with time delay enforced).
* @param newBound New deviation bound for target allocation.
* @return `true` if successful.
*/
function prepareBound(uint256 newBound) external onlyGovernance returns (bool) {
require(newBound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT);
return _prepare(_BOUND_KEY, newBound);
}
/**
* @notice Execute update of deviation bound for strategy allocation (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New deviation bound.
*/
function executeBound() external returns (uint256) {
uint256 bound = _executeUInt256(_BOUND_KEY);
_deposit();
return bound;
}
function resetBound() external onlyGovernance returns (bool) {
return _resetUInt256Config(_BOUND_KEY);
}
/**
* @notice Withdraws an amount of underlying from the strategy to the vault.
* @param amount Amount of underlying to withdraw.
* @return True if successful withdrawal.
*/
function withdrawFromStrategy(uint256 amount) external onlyGovernance returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
if (strategy.balance() < amount) return false;
uint256 oldBalance = _availableUnderlying();
strategy.withdraw(amount);
uint256 newBalance = _availableUnderlying();
currentAllocated -= newBalance - oldBalance;
return true;
}
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256) {
(bool exists, uint256 allocated) = _strategiesWaitingForRemoval.tryGet(strategy);
require(exists, Error.STRATEGY_DOES_NOT_EXIST);
IStrategy strategy_ = IStrategy(strategy);
strategy_.harvest();
uint256 withdrawn = strategy_.withdrawAll();
uint256 _waitingForRemovalAllocated = waitingForRemovalAllocated;
if (withdrawn >= _waitingForRemovalAllocated) {
waitingForRemovalAllocated = 0;
} else {
waitingForRemovalAllocated = _waitingForRemovalAllocated - withdrawn;
}
if (withdrawn > allocated) {
uint256 profit = withdrawn - allocated;
uint256 strategistShare = _shareFees(profit.scaledMul(getPerformanceFee()));
if (strategistShare > 0) {
_payStrategist(strategistShare, strategy_.strategist());
}
allocated = 0;
emit Harvest(profit, 0);
} else {
allocated -= withdrawn;
}
if (strategy_.balance() == 0) {
_strategiesWaitingForRemoval.remove(address(strategy_));
} else {
_strategiesWaitingForRemoval.set(address(strategy_), allocated);
}
return withdrawn;
}
function getStrategiesWaitingForRemoval() external view returns (address[] memory) {
return _strategiesWaitingForRemoval.keysArray();
}
/**
* @notice Computes the total underlying of the vault: idle funds + allocated funds - debt
* @return Total amount of underlying.
*/
function getTotalUnderlying() external view override returns (uint256) {
uint256 availableUnderlying_ = _availableUnderlying();
if (address(getStrategy()) == address(0)) {
return availableUnderlying_;
}
uint256 netUnderlying = availableUnderlying_ +
currentAllocated +
waitingForRemovalAllocated;
if (totalDebt <= netUnderlying) return netUnderlying - totalDebt;
return 0;
}
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256)
{
return _strategiesWaitingForRemoval.get(strategy);
}
/**
* @notice Withdraws all funds from strategy to vault.
* @dev Harvests profits before withdrawing. Deactivates strategy after withdrawing.
* @return `true` if successful.
*/
function withdrawAllFromStrategy() public onlyPoolOrGovernance returns (bool) {
return _withdrawAllFromStrategy();
}
/**
* @notice Harvest profits from the vault's strategy.
* @dev Harvesting adds profits to the vault's balance and deducts fees.
* No performance fees are charged on profit used to repay debt.
* @return `true` if successful.
*/
function harvest() public onlyPoolOrMaintenance returns (bool) {
return _harvest();
}
/**
* @notice Returns the percentage of the performance fee that goes to the strategist.
*/
function getStrategistFee() public view returns (uint256) {
return currentUInts256[_STRATEGIST_FEE_KEY];
}
function getStrategy() public view override returns (IStrategy) {
return IStrategy(currentAddresses[_STRATEGY_KEY]);
}
/**
* @notice Returns the percentage of the performance fee which is allocated to the vault reserve
*/
function getReserveFee() public view returns (uint256) {
return currentUInts256[_RESERVE_FEE_KEY];
}
/**
* @notice Returns the fee charged on a strategy's generated profits.
* @dev The strategist is paid in LP tokens, while the remainder of the profit stays in the vault.
* Default performance fee is set to 5% of harvested profits.
*/
function getPerformanceFee() public view returns (uint256) {
return currentUInts256[_PERFORMANCE_FEE_KEY];
}
/**
* @notice Returns the allowed symmetric bound for target allocation (e.g. +- 5%)
*/
function getBound() public view returns (uint256) {
return currentUInts256[_BOUND_KEY];
}
/**
* @notice The target percentage of total underlying funds to be allocated towards a strategy.
* @dev this is to reduce gas costs. Withdrawals first come from idle funds and can therefore
* avoid unnecessary gas costs.
*/
function getTargetAllocation() public view returns (uint256) {
return currentUInts256[_TARGET_ALLOCATION_KEY];
}
/**
* @notice The debt limit that the total debt of a strategy may not exceed.
*/
function getDebtLimit() public view returns (uint256) {
return currentUInts256[_DEBT_LIMIT_KEY];
}
function getUnderlying() public view virtual override returns (address);
function _activateStrategy() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
strategyActive = true;
emit StrategyActivated(address(strategy));
_deposit();
return true;
}
function _harvest() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) {
return false;
}
strategy.harvest();
uint256 strategistShare = 0;
uint256 allocatedUnderlying = strategy.balance();
uint256 amountAllocated = currentAllocated;
uint256 currentDebt = totalDebt;
if (allocatedUnderlying > amountAllocated) {
// we made profits
uint256 profit = allocatedUnderlying - amountAllocated;
if (profit > currentDebt) {
if (currentDebt > 0) {
profit -= currentDebt;
currentDebt = 0;
}
(profit, strategistShare) = _shareProfit(profit);
} else {
currentDebt -= profit;
}
emit Harvest(profit, 0);
} else if (allocatedUnderlying < amountAllocated) {
// we made a loss
uint256 loss = amountAllocated - allocatedUnderlying;
currentDebt += loss;
// check debt limit and withdraw funds if exceeded
uint256 debtLimit = getDebtLimit();
uint256 debtLimitAllocated = amountAllocated.scaledMul(debtLimit);
if (currentDebt > debtLimitAllocated) {
currentDebt = _handleExcessDebt(currentDebt);
}
emit Harvest(0, loss);
} else {
// nothing to declare
return true;
}
totalDebt = currentDebt;
currentAllocated = strategy.balance();
if (strategistShare > 0) {
_payStrategist(strategistShare);
}
return true;
}
function _withdrawAllFromStrategy() internal returns (bool) {
IStrategy strategy = getStrategy();
if (address(strategy) == address(0)) return false;
_harvest();
uint256 oldBalance = _availableUnderlying();
strategy.withdrawAll();
uint256 newBalance = _availableUnderlying();
uint256 withdrawnAmount = newBalance - oldBalance;
currentAllocated = _computeNewAllocated(currentAllocated, withdrawnAmount);
_deactivateStrategy();
return true;
}
function _handleExcessDebt(uint256 currentDebt) internal returns (uint256) {
uint256 underlyingReserves = reserve.getBalance(address(this), getUnderlying());
if (currentDebt > underlyingReserves) {
_emergencyStop(underlyingReserves);
} else if (reserve.canWithdraw(address(this))) {
reserve.withdraw(getUnderlying(), currentDebt);
currentDebt = 0;
_deposit();
}
return currentDebt;
}
function _handleExcessDebt() internal {
uint256 currentDebt = totalDebt;
uint256 newDebt = _handleExcessDebt(totalDebt);
if (currentDebt != newDebt) {
totalDebt = newDebt;
}
}
/**
* @notice Invest the underlying money in the vault after a deposit from the pool is made.
* @dev After each deposit, the vault checks whether it needs to rebalance underlying funds allocated to strategy.
* If no strategy is set then all deposited funds will be idle.
*/
function _deposit() internal {
if (!strategyActive) return;
uint256 allocatedUnderlying = getStrategy().balance();
uint256 totalUnderlying = _availableUnderlying() +
allocatedUnderlying +
waitingForRemovalAllocated;
if (totalUnderlying == 0) return;
_rebalance(totalUnderlying, allocatedUnderlying);
}
function _shareProfit(uint256 profit) internal returns (uint256, uint256) {
uint256 totalFeeAmount = profit.scaledMul(getPerformanceFee());
if (_availableUnderlying() < totalFeeAmount) {
getStrategy().withdraw(totalFeeAmount);
}
uint256 strategistShare = _shareFees(totalFeeAmount);
return ((profit - totalFeeAmount), strategistShare);
}
function _shareFees(uint256 totalFeeAmount) internal returns (uint256) {
uint256 strategistShare = totalFeeAmount.scaledMul(getStrategistFee());
uint256 reserveShare = totalFeeAmount.scaledMul(getReserveFee());
uint256 treasuryShare = totalFeeAmount - strategistShare - reserveShare;
_depositToReserve(reserveShare);
if (treasuryShare > 0) {
_depositToTreasury(treasuryShare);
}
return strategistShare;
}
function _emergencyStop(uint256 underlyingReserves) internal {
// debt limit exceeded: withdraw funds from strategy
uint256 withdrawn = getStrategy().withdrawAll();
uint256 actualDebt = _computeNewAllocated(currentAllocated, withdrawn);
if (reserve.canWithdraw(address(this))) {
// check if debt can be covered with reserve funds
if (underlyingReserves >= actualDebt) {
reserve.withdraw(getUnderlying(), actualDebt);
} else if (underlyingReserves > 0) {
// debt can not be covered with reserves
reserve.withdraw(getUnderlying(), underlyingReserves);
}
}
// too much money lost, stop the strategy
_deactivateStrategy();
}
/**
* @notice Deactivates a strategy. All positions of the strategy are exited.
* @return `true` if strategy has been deactivated
*/
function _deactivateStrategy() internal returns (bool) {
if (!strategyActive) return false;
strategyActive = false;
emit StrategyDeactivated(address(getStrategy()));
return true;
}
function _payStrategist(uint256 amount) internal {
_payStrategist(amount, getStrategy().strategist());
}
function _payStrategist(uint256 amount, address strategist) internal virtual;
function _transfer(address to, uint256 amount) internal virtual;
function _depositToReserve(uint256 amount) internal virtual;
function _depositToTreasury(uint256 amount) internal virtual;
function _availableUnderlying() internal view virtual returns (uint256);
function _computeNewAllocated(uint256 allocated, uint256 withdrawn)
internal
pure
returns (uint256)
{
if (allocated > withdrawn) {
return allocated - withdrawn;
}
return 0;
}
function _checkFeesInvariant(uint256 reserveFee, uint256 strategistFee) internal pure {
require(
reserveFee + strategistFee <= ScaledMath.ONE,
"sum of strategist fee and reserve fee should be below 1"
);
}
function _rebalance(uint256 totalUnderlying, uint256 allocatedUnderlying)
private
returns (bool)
{
if (!strategyActive) return false;
uint256 targetAllocation = getTargetAllocation();
IStrategy strategy = getStrategy();
uint256 bound = getBound();
uint256 target = totalUnderlying.scaledMul(targetAllocation);
uint256 upperBound = targetAllocation == 0 ? 0 : targetAllocation + bound;
upperBound = upperBound > ScaledMath.ONE ? ScaledMath.ONE : upperBound;
uint256 lowerBound = bound > targetAllocation ? 0 : targetAllocation - bound;
if (allocatedUnderlying > totalUnderlying.scaledMul(upperBound)) {
// withdraw funds from strategy
uint256 withdrawAmount = allocatedUnderlying - target;
strategy.withdraw(withdrawAmount);
currentAllocated = _computeNewAllocated(currentAllocated, withdrawAmount);
} else if (allocatedUnderlying < totalUnderlying.scaledMul(lowerBound)) {
// allocate more funds to strategy
uint256 depositAmount = target - allocatedUnderlying;
_transfer(address(strategy), depositAmount);
currentAllocated += depositAmount;
strategy.deposit();
}
return true;
}
}
// File contracts/vault/EthVault.sol
pragma solidity 0.8.9;
contract EthVault is Vault {
using AddressProviderHelpers for IAddressProvider;
address private constant _UNDERLYING = address(0);
constructor(IController controller) Vault(controller) {}
receive() external payable {}
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external virtual override initializer {
_initialize(_pool, _debtLimit, _targetAllocation, _bound);
}
function getUnderlying() public pure override returns (address) {
return _UNDERLYING;
}
function _transfer(address to, uint256 amount) internal override {
payable(to).transfer(amount);
}
function _depositToReserve(uint256 amount) internal override {
reserve.deposit{value: amount}(_UNDERLYING, amount);
}
function _depositToTreasury(uint256 amount) internal override {
payable(addressProvider.getTreasury()).transfer(amount);
}
function _payStrategist(uint256 amount, address strategist) internal override {
if (strategist == address(0)) return;
ILiquidityPool(pool).depositFor{value: amount}(strategist, amount);
}
function _availableUnderlying() internal view override returns (uint256) {
return address(this).balance;
}
} | Withdraws specified amount of underlying from reserve to vault. Withdraws from reserve will cause a spike in pool exchange rate. Pool deposits should be paused during this to prevent front running amount Amount to withdraw./ | function withdrawFromReserve(uint256 amount) external override onlyGovernance {
require(amount > 0, Error.INVALID_AMOUNT);
require(IPausable(pool).isPaused(), Error.POOL_NOT_PAUSED);
uint256 reserveBalance_ = reserve.getBalance(address(this), getUnderlying());
require(amount <= reserveBalance_, Error.INSUFFICIENT_BALANCE);
reserve.withdraw(getUnderlying(), amount);
}
| 6,639,023 |
./full_match/5/0x83E9e16C865e04b52F1f8f9d0BbabDd762403809/sources/project_/contracts/MARToken.sol | Moves `amount` of tokens from `from` to `to`. 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. | function _transfer(address from, address to, uint256 amount) private {
require(from != address(0) && to != address(0), 'MARToken: zero address not allowed');
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, 'MARToken: transfer amount exceeds balance');
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
| 1,882,882 |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
} else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (governor) that can be granted exclusive access to
* specific functions.
*
* By default, the governor account will be the one that deploys the contract. This
* can later be changed with {transferGovernorship}.
*
*/
contract Governed is Context, Initializable {
address public governor;
address private proposedGovernor;
event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);
/**
* @dev Initializes the contract setting the deployer as the initial governor.
*/
constructor() {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev If inheriting child is using proxy then child contract can use
* _initializeGoverned() function to initialization this contract
*/
function _initializeGoverned() internal initializer {
address msgSender = _msgSender();
governor = msgSender;
emit UpdatedGovernor(address(0), msgSender);
}
/**
* @dev Throws if called by any account other than the governor.
*/
modifier onlyGovernor {
require(governor == _msgSender(), "not-the-governor");
_;
}
/**
* @dev Transfers governorship of the contract to a new account (`proposedGovernor`).
* Can only be called by the current owner.
*/
function transferGovernorship(address _proposedGovernor) external onlyGovernor {
require(_proposedGovernor != address(0), "proposed-governor-is-zero");
proposedGovernor = _proposedGovernor;
}
/**
* @dev Allows new governor to accept governorship of the contract.
*/
function acceptGovernorship() external {
require(proposedGovernor == _msgSender(), "not-the-proposed-governor");
emit UpdatedGovernor(governor, proposedGovernor);
governor = proposedGovernor;
proposedGovernor = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not-paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "not-shutdown");
_;
}
/// @dev Pause contract operations, if contract is not paused.
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
/// @dev Unpause contract operations, allow only if contract is paused and not shutdown.
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
/// @dev Shutdown contract operations, if not already shutdown.
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
/// @dev Open contract operations, if contract is in shutdown state
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolAccountant {
function decreaseDebt(address _strategy, uint256 _decreaseBy) external;
function migrateStrategy(address _old, address _new) external;
function reportEarning(
address _strategy,
uint256 _profit,
uint256 _loss,
uint256 _payback
)
external
returns (
uint256 _actualPayback,
uint256 _creditLine,
uint256 _interestFee
);
function reportLoss(address _strategy, uint256 _loss) external;
function availableCreditLimit(address _strategy) external view returns (uint256);
function excessDebt(address _strategy) external view returns (uint256);
function getStrategies() external view returns (address[] memory);
function getWithdrawQueue() external view returns (address[] memory);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function totalDebt() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalDebtRatio() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPoolRewards {
/// Emitted after reward added
event RewardAdded(uint256 reward);
/// Emitted whenever any user claim rewards
event RewardPaid(address indexed user, uint256 reward);
/// Emitted when reward is ended
event RewardEnded(address indexed dustReceiver, uint256 dust);
// Emitted when pool governor update reward end time
event UpdatedRewardEndTime(uint256 previousRewardEndTime, uint256 newRewardEndTime);
function claimReward(address) external;
function notifyRewardAmount(uint256 rewardAmount, uint256 endTime) external;
function updateRewardEndTime() external;
function updateReward(address) external;
function withdrawRemaining(address _toAddress) external;
function claimable(address) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardForDuration() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/// @title Errors library
library Errors {
string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0
string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0
string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0
string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length
string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee
string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed
string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set
string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep
string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow
string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero
string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS
string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again
string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list
string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list
string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required
string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required
string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool
string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS
string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0
string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// solhint-disable reason-string, no-empty-blocks
///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20
abstract contract PoolERC20 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}.
*/
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 decimals of the token. default to 18
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev Returns total supply of the token.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _setName(string memory name_) internal {
_name = name_;
}
function _setSymbol(string memory symbol_) internal {
_symbol = symbol_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./PoolERC20.sol";
///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit
// solhint-disable var-name-mixedcase
abstract contract PoolERC20Permit is PoolERC20, IERC20Permit {
bytes32 private constant _EIP712_VERSION = keccak256(bytes("1"));
bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private _CACHED_DOMAIN_SEPARATOR;
bytes32 private _HASHED_NAME;
uint256 private _CACHED_CHAIN_ID;
/**
* @dev See {IERC20Permit-nonces}.
*/
mapping(address => uint256) public override nonces;
/**
* @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`.
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function _initializePermit(string memory name_) internal {
_HASHED_NAME = keccak256(bytes(name_));
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
uint256 _currentNonce = nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline));
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
nonces[owner] = _currentNonce + 1;
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() private view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./PoolERC20Permit.sol";
import "./PoolStorage.sol";
import "./Errors.sol";
import "../Governed.sol";
import "../Pausable.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/vesper/IPoolRewards.sol";
/// @title Holding pool share token
// solhint-disable no-empty-blocks
abstract contract PoolShareToken is Initializable, PoolStorageV1, PoolERC20Permit, Governed, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 public constant MAX_BPS = 10_000;
event Deposit(address indexed owner, uint256 shares, uint256 amount);
event Withdraw(address indexed owner, uint256 shares, uint256 amount);
constructor(
string memory _name,
string memory _symbol,
address _token
) PoolERC20(_name, _symbol) {
token = IERC20(_token);
}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializePool(
string memory _name,
string memory _symbol,
address _token
) internal initializer {
_setName(_name);
_setSymbol(_symbol);
_initializePermit(_name);
token = IERC20(_token);
// Assuming token supports 18 or less decimals
uint256 _decimals = IERC20Metadata(_token).decimals();
decimalConversionFactor = _decimals == 18 ? 1 : 10**(18 - _decimals);
}
/**
* @notice Deposit ERC20 tokens and receive pool shares depending on the current share price.
* @param _amount ERC20 token amount.
*/
function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused {
_deposit(_amount);
}
/**
* @notice Deposit ERC20 tokens with permit aka gasless approval.
* @param _amount ERC20 token amount.
* @param _deadline The time at which signature will expire
* @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 depositWithPermit(
uint256 _amount,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external virtual nonReentrant whenNotPaused {
IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s);
_deposit(_amount);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector.
* Burn remaining shares and return collateral.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
_withdraw(_shares);
}
/**
* @notice Withdraw collateral based on given shares and the current share price.
* @dev Burn shares and return collateral. No withdraw fee will be assessed
* when this function is called. Only some white listed address can call this function.
* @param _shares Pool shares. It will be in 18 decimals.
*/
function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown {
require(IAddressList(feeWhitelist).contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS);
_withdrawWithoutFee(_shares);
}
/**
* @notice Transfer tokens to multiple recipient
* @dev Address array and amount array are 1:1 and are in order.
* @param _recipients array of recipient addresses
* @param _amounts array of token amounts
* @return true/false
*/
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) {
require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH);
for (uint256 i = 0; i < _recipients.length; i++) {
require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED);
}
return true;
}
/**
* @notice Get price per share
* @dev Return value will be in token defined decimals.
*/
function pricePerShare() public view returns (uint256) {
if (totalSupply() == 0 || totalValue() == 0) {
return convertFrom18(1e18);
}
return (totalValue() * 1e18) / totalSupply();
}
/// @dev Convert from 18 decimals to token defined decimals.
function convertFrom18(uint256 _amount) public view virtual returns (uint256) {
return _amount / decimalConversionFactor;
}
/// @dev Returns the token stored in the pool. It will be in token defined decimals.
function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Returns sum of token locked in other contracts and token stored in the pool.
* Default tokensHere. It will be in token defined decimals.
*/
function totalValue() public view virtual returns (uint256);
/**
* @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue
* @param _share Pool share in 18 decimals
*/
function _beforeBurning(uint256 _share) internal virtual returns (uint256) {}
/**
* @dev Hook that is called just after burning tokens.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterBurning(uint256 _amount) internal virtual returns (uint256) {
token.safeTransfer(_msgSender(), _amount);
return _amount;
}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred from user to this contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _beforeMinting(uint256 _amount) internal virtual {
token.safeTransferFrom(_msgSender(), address(this), _amount);
}
/**
* @dev Hook that is called just after minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
* @param _amount Collateral amount in collateral token defined decimals.
*/
function _afterMinting(uint256 _amount) internal virtual {}
/// @dev Update pool rewards of sender and receiver during transfer.
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).updateReward(sender);
IPoolRewards(poolRewards).updateReward(recipient);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Calculate shares to mint based on the current share price and given amount.
* @param _amount Collateral amount in collateral token defined decimals.
* @return share amount in 18 decimal
*/
function _calculateShares(uint256 _amount) internal view returns (uint256) {
require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT);
uint256 _share = ((_amount * 1e18) / pricePerShare());
return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share;
}
/// @notice claim rewards of account
function _claimRewards(address _account) internal {
if (poolRewards != address(0)) {
IPoolRewards(poolRewards).claimReward(_account);
}
}
/// @dev Deposit incoming token and mint pool token i.e. shares.
function _deposit(uint256 _amount) internal {
_claimRewards(_msgSender());
uint256 _shares = _calculateShares(_amount);
_beforeMinting(_amount);
_mint(_msgSender(), _shares);
_afterMinting(_amount);
emit Deposit(_msgSender(), _shares, _amount);
}
/// @dev Burns shares and returns the collateral value, after fee, of those.
function _withdraw(uint256 _shares) internal {
if (withdrawFee == 0) {
_withdrawWithoutFee(_shares);
} else {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _fee = (_shares * withdrawFee) / MAX_BPS;
uint256 _sharesAfterFee = _shares - _fee;
uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee);
// Recalculate proportional share on actual amount withdrawn
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
// Using convertFrom18() to avoid dust.
// Pool share token is in 18 decimal and collateral token decimal is <=18.
// Anything less than 10**(18-collateralTokenDecimal) is dust.
if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) {
// Recalculate shares to withdraw, fee and shareAfterFee
_shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee);
_fee = _shares - _proportionalShares;
_sharesAfterFee = _proportionalShares;
}
_burn(_msgSender(), _sharesAfterFee);
_transfer(_msgSender(), feeCollector, _fee);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
/// @dev Burns shares and returns the collateral value of those.
function _withdrawWithoutFee(uint256 _shares) internal {
require(_shares != 0, Errors.INVALID_SHARE_AMOUNT);
_claimRewards(_msgSender());
uint256 _amountWithdrawn = _beforeBurning(_shares);
uint256 _proportionalShares = _calculateShares(_amountWithdrawn);
if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) {
_shares = _proportionalShares;
}
_burn(_msgSender(), _shares);
_afterBurning(_amountWithdrawn);
emit Withdraw(_msgSender(), _shares, _amountWithdrawn);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract PoolStorageV1 {
IERC20 public token; // Collateral token
address public poolAccountant; // PoolAccountant address
address public poolRewards; // PoolRewards contract address
address public feeWhitelist; // sol-address-list address which contains whitelisted addresses to withdraw without fee
address public keepers; // sol-address-list address which contains addresses of keepers
address public maintainers; // sol-address-list address which contains addresses of maintainers
address public feeCollector; // Fee collector address
uint256 public withdrawFee; // Withdraw fee for this pool
uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals
bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./VPoolBase.sol";
//solhint-disable no-empty-blocks
contract VPool is VPoolBase {
string public constant VERSION = "3.0.3";
constructor(
string memory _name,
string memory _symbol,
address _token
) VPoolBase(_name, _symbol, _token) {}
function initialize(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) public initializer {
_initializeBase(_name, _symbol, _token, _poolAccountant, _addressListFactory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Errors.sol";
import "./PoolShareToken.sol";
import "../interfaces/vesper/IPoolAccountant.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
abstract contract VPoolBase is PoolShareToken {
using SafeERC20 for IERC20;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards);
event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee);
constructor(
string memory _name,
string memory _symbol,
address _token // solhint-disable-next-line no-empty-blocks
) PoolShareToken(_name, _symbol, _token) {}
/// @dev Equivalent to constructor for proxy. It can be called only once per proxy.
function _initializeBase(
string memory _name,
string memory _symbol,
address _token,
address _poolAccountant,
address _addressListFactory
) internal initializer {
_initializePool(_name, _symbol, _token);
_initializeGoverned();
_initializeAddressLists(_addressListFactory);
poolAccountant = _poolAccountant;
}
/**
* @notice Create feeWhitelist, keeper and maintainer list
* @dev Add caller into the keeper and maintainer list
* @dev This function will be used as part of initializer
* @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param
* ethereum - 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3
* polygon - 0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291
*/
function _initializeAddressLists(address _addressListFactory) internal {
require(address(keepers) == address(0), Errors.ALREADY_INITIALIZED);
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
feeWhitelist = _factory.createList();
keepers = _factory.createList();
maintainers = _factory.createList();
// List creator can do job of keeper and maintainer.
IAddressList(keepers).add(_msgSender());
IAddressList(maintainers).add(_msgSender());
}
modifier onlyKeeper() {
require(IAddressList(keepers).contains(_msgSender()), "not-a-keeper");
_;
}
modifier onlyMaintainer() {
require(IAddressList(maintainers).contains(_msgSender()), "not-a-maintainer");
_;
}
////////////////////////////// Only Governor //////////////////////////////
/**
* @notice Migrate existing strategy to new strategy.
* @dev Migrating strategy aka old and new strategy should be of same type.
* @param _old Address of strategy being migrated
* @param _new Address of new strategy
*/
function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
/**
* @notice Update fee collector address for this pool
* @param _newFeeCollector new fee collector address
*/
function updateFeeCollector(address _newFeeCollector) external onlyGovernor {
require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedFeeCollector(feeCollector, _newFeeCollector);
feeCollector = _newFeeCollector;
}
/**
* @notice Update pool rewards address for this pool
* @param _newPoolRewards new pool rewards address
*/
function updatePoolRewards(address _newPoolRewards) external onlyGovernor {
require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO);
emit UpdatedPoolRewards(poolRewards, _newPoolRewards);
poolRewards = _newPoolRewards;
}
/**
* @notice Update withdraw fee for this pool
* @dev Format: 1500 = 15% fee, 100 = 1%
* @param _newWithdrawFee new withdraw fee
*/
function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor {
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED);
emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee);
withdrawFee = _newWithdrawFee;
}
///////////////////////////// Only Keeper ///////////////////////////////
function pause() external onlyKeeper {
_pause();
}
function unpause() external onlyKeeper {
_unpause();
}
function shutdown() external onlyKeeper {
_shutdown();
}
function open() external onlyKeeper {
_open();
}
/**
* @notice Add given address in provided address list.
* @dev Use it to add keeper in keepers list and to add address in feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToAdd address which we want to add in AddressList.
*/
function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper {
require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
/**
* @notice Remove given address from provided address list.
* @dev Use it to remove keeper from keepers list and to remove address from feeWhitelist
* @param _listToUpdate address of AddressList contract.
* @param _addressToRemove address which we want to remove from AddressList.
*/
function removeFromList(address _listToUpdate, address _addressToRemove) external onlyKeeper {
require(IAddressList(_listToUpdate).remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED);
}
///////////////////////////////////////////////////////////////////////////
/**
* @dev Strategy call this in regular interval.
* @param _profit yield generated by strategy. Strategy get performance fee on this amount
* @param _loss Reduce debt ,also reduce debtRatio, increase loss in record.
* @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount.
* when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately.
*/
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external {
(uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) =
IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback);
uint256 _totalPayback = _profit + _actualPayback;
// After payback, if strategy has credit line available then send more fund to strategy
// If payback is more than available credit line then get fund from strategy
if (_totalPayback < _creditLine) {
token.safeTransfer(_msgSender(), _creditLine - _totalPayback);
} else if (_totalPayback > _creditLine) {
token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine);
}
// Mint interest fee worth shares at strategy address
if (_interestFee != 0) {
_mint(_msgSender(), _calculateShares(_interestFee));
}
}
/**
* @notice Report loss outside of rebalance activity.
* @dev Some strategies pay deposit fee thus realizing loss at deposit.
* For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool.
* Strategy may want report this loss instead of waiting for next rebalance.
* @param _loss Loss that strategy want to report
*/
function reportLoss(uint256 _loss) external {
IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss);
}
/**
* @dev Transfer given ERC20 token to feeCollector
* @param _fromToken Token address to sweep
*/
function sweepERC20(address _fromToken) external virtual onlyKeeper {
require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP);
require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET);
IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this)));
}
/**
* @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool
* @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy.
* credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance)
* when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool
* @param _strategy Strategy address
*/
function availableCreditLimit(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy);
}
/**
* @notice Debt above current debt limit
* @param _strategy Address of strategy
*/
function excessDebt(address _strategy) external view returns (uint256) {
return IPoolAccountant(poolAccountant).excessDebt(_strategy);
}
function getStrategies() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getStrategies();
}
function getWithdrawQueue() public view returns (address[] memory) {
return IPoolAccountant(poolAccountant).getWithdrawQueue();
}
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
)
{
return IPoolAccountant(poolAccountant).strategy(_strategy);
}
/// @notice Get total debt of pool
function totalDebt() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt();
}
/**
* @notice Get total debt of given strategy
* @param _strategy Strategy address
*/
function totalDebtOf(address _strategy) public view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtOf(_strategy);
}
/// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool
function totalDebtRatio() external view returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebtRatio();
}
/// @dev Returns total value of vesper pool, in terms of collateral token
function totalValue() public view override returns (uint256) {
return IPoolAccountant(poolAccountant).totalDebt() + tokensHere();
}
function _withdrawCollateral(uint256 _amount) internal virtual {
// Withdraw amount from queue
uint256 _debt;
uint256 _balanceAfter;
uint256 _balanceBefore;
uint256 _amountWithdrawn;
uint256 _amountNeeded = _amount;
uint256 _totalAmountWithdrawn;
address[] memory _withdrawQueue = getWithdrawQueue();
for (uint256 i; i < _withdrawQueue.length; i++) {
_debt = totalDebtOf(_withdrawQueue[i]);
if (_debt == 0) {
continue;
}
if (_amountNeeded > _debt) {
// Should not withdraw more than current debt of strategy.
_amountNeeded = _debt;
}
_balanceBefore = tokensHere();
//solhint-disable no-empty-blocks
try IStrategy(_withdrawQueue[i]).withdraw(_amountNeeded) {} catch {
continue;
}
_balanceAfter = tokensHere();
_amountWithdrawn = _balanceAfter - _balanceBefore;
// Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded
IPoolAccountant(poolAccountant).decreaseDebt(_withdrawQueue[i], _amountWithdrawn);
_totalAmountWithdrawn += _amountWithdrawn;
if (_totalAmountWithdrawn >= _amount) {
// withdraw done
break;
}
_amountNeeded = _amount - _totalAmountWithdrawn;
}
}
/**
* @dev Before burning hook.
* withdraw amount from strategies
*/
function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {
uint256 _amount = (_share * pricePerShare()) / 1e18;
uint256 _balanceNow = tokensHere();
if (_amount > _balanceNow) {
_withdrawCollateral(_amount - _balanceNow);
_balanceNow = tokensHere();
}
actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount;
}
}
| Add given address in provided address list. Use it to add keeper in keepers list and to add address in feeWhitelist _listToUpdate address of AddressList contract. _addressToAdd address which we want to add in AddressList./ | function addInList(address _listToUpdate, address _addressToAdd) external onlyKeeper {
require(IAddressList(_listToUpdate).add(_addressToAdd), Errors.ADD_IN_LIST_FAILED);
}
| 166,377 |
/**
* Copyright 2017-2019, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.3;
pragma experimental ABIEncoderV2;
import "../openzeppelin-solidity/Math.sol";
import "../proxy/BZxProxiable.sol";
import "../shared/OrderClosingFunctions.sol";
import "../BZxVault.sol";
import "../oracle/OracleInterface.sol";
contract LoanHealth_MiscFunctions3 is BZxStorage, BZxProxiable, OrderClosingFunctions {
using SafeMath for uint256;
constructor() public {}
function()
external
{
revert("fallback not allowed");
}
function initialize(
address _target)
public
onlyOwner
{
targets[bytes4(keccak256("closeLoanPartially(bytes32,uint256)"))] = _target;
targets[bytes4(keccak256("closeLoanPartiallyIfHealthy(bytes32,uint256)"))] = _target;
targets[bytes4(keccak256("closeLoanPartiallyFromCollateral(bytes32,uint256)"))] = _target;
}
/// @dev Called by the trader to close part of their loan early.
/// @param loanOrderHash A unique hash representing the loan order
/// @param closeAmount The amount of the loan token to return to the lender
/// @return The actual amount closed. Greater than closeAmount means the loan needed liquidation.
function closeLoanPartially(
bytes32 loanOrderHash,
uint256 closeAmount)
external
nonReentrant
tracksGas
returns (uint256 actualCloseAmount)
{
if (closeAmount == 0) {
return 0;
}
LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][msg.sender]];
if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) {
return 0;
}
LoanOrder memory loanOrder = orders[loanOrderHash];
if (loanOrder.loanTokenAddress == address(0)) {
revert("_closeLoanPartially: loanOrder.loanTokenAddress == address(0)");
}
return _closeLoanPartially(
loanOrder,
loanPosition,
closeAmount,
0, // collateralCloseAmount (calculated later)
0, // marginAmountBeforeClose (calculated later)
oracleAddresses[loanOrder.oracleAddress],
false, // ensureHealthy
gasUsed // initial used gas, collected in modifier
);
}
/// @dev Called by the trader to close part of their loan early.
/// @dev Contract will revert if the position is unhealthy and the full position is not being closed.
/// @param loanOrderHash A unique hash representing the loan order
/// @param closeAmount The amount of the loan token to return to the lender
/// @return The actual amount closed. Greater than closeAmount means the loan needed liquidation.
function closeLoanPartiallyIfHealthy(
bytes32 loanOrderHash,
uint256 closeAmount)
external
nonReentrant
tracksGas
returns (uint256 actualCloseAmount)
{
if (closeAmount == 0) {
return 0;
}
LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][msg.sender]];
if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) {
return 0;
}
LoanOrder memory loanOrder = orders[loanOrderHash];
if (loanOrder.loanTokenAddress == address(0)) {
revert("_closeLoanPartially: loanOrder.loanTokenAddress == address(0)");
}
return _closeLoanPartially(
loanOrder,
loanPosition,
closeAmount,
0, // collateralCloseAmount (calculated later)
0, // marginAmountBeforeClose (calculated later)
oracleAddresses[loanOrder.oracleAddress],
true, // ensureHealthy
gasUsed // initial used gas, collected in modifier
);
}
/// @dev Called by the trader to close part of their loan early.
/// @dev Contract will revert if the position is unhealthy and the full position is not being closed.
/// @param loanOrderHash A unique hash representing the loan order
/// @param closeAmount The amount of collateral token to close out. Loan amount to close will be calculated based on current margin.
/// @return The actual amount of loan token closed. Greater than closeAmount means the loan needed liquidation.
function closeLoanPartiallyFromCollateral(
bytes32 loanOrderHash,
uint256 closeAmount)
external
nonReentrant
tracksGas
returns (uint256 actualCloseAmount)
{
if (closeAmount == 0) {
return 0;
}
LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][msg.sender]];
if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) {
return 0;
}
LoanOrder memory loanOrder = orders[loanOrderHash];
if (loanOrder.loanTokenAddress == address(0)) {
revert("_closeLoanPartially: loanOrder.loanTokenAddress == address(0)");
}
address oracleAddress = oracleAddresses[loanOrder.oracleAddress];
uint256 marginAmountBeforeClose;
uint256 collateralCloseAmount;
uint256 updatedCloseAmount;
if (closeAmount < loanPosition.collateralTokenAmountFilled) {
marginAmountBeforeClose = _getCurrentMarginAmount(
loanOrder,
loanPosition,
oracleAddress
);
if (marginAmountBeforeClose <= loanOrder.maintenanceMarginAmount) {
revert("BZxLoanHealth::_closeLoanPartially: unhealthy position");
}
collateralCloseAmount = closeAmount;
updatedCloseAmount = collateralCloseAmount
.mul(10**20)
.div(marginAmountBeforeClose);
if (loanPosition.collateralTokenAddressFilled != loanOrder.loanTokenAddress) {
(uint256 sourceToDestRate, uint256 sourceToDestPrecision,) = OracleInterface(oracleAddress).getTradeData(
loanOrder.loanTokenAddress,
loanPosition.collateralTokenAddressFilled,
MAX_UINT // get best rate
);
updatedCloseAmount = updatedCloseAmount
.mul(sourceToDestPrecision)
.div(sourceToDestRate);
/*(,,updatedCloseAmount) = OracleInterface(oracleAddress).getTradeData(
loanPosition.collateralTokenAddressFilled,
loanOrder.loanTokenAddress,
collateralCloseAmount
);
updatedCloseAmount = updatedCloseAmount
.mul(sourceToDestRate)
.div(sourceToDestPrecision)
.mul(10**20)
.div(marginAmountBeforeClose);*/
/*(,,updatedCloseAmount) = OracleInterface(oracleAddress).getTradeData(
loanPosition.collateralTokenAddressFilled,
loanOrder.loanTokenAddress,
updatedCloseAmount
);*/
}
} else {
// this will trigger closing the entire loan amount
collateralCloseAmount = loanPosition.collateralTokenAmountFilled;
updatedCloseAmount = MAX_UINT;
}
return _closeLoanPartially(
loanOrder,
loanPosition,
updatedCloseAmount,
collateralCloseAmount,
marginAmountBeforeClose,
oracleAddress,
true, // ensureHealthy
gasUsed // initial used gas, collected in modifier
);
}
/*
* Internal functions
*/
function _closeLoanPartially(
LoanOrder memory loanOrder,
LoanPosition storage loanPosition,
uint256 closeAmount,
uint256 collateralCloseAmount,
uint256 marginAmountBeforeClose,
address oracleAddress,
bool ensureHealthy,
uint256 gasUsed)
internal
returns (uint256)
{
if (closeAmount >= loanPosition.loanTokenAmountFilled) {
closeAmount = loanPosition.loanTokenAmountFilled; // save before storage update
// close entire loan requested
ensureHealthy = _closeLoan(
loanOrder.loanOrderHash,
msg.sender, // borrower
gasUsed // initial used gas, collected in modifier
);
if (ensureHealthy)
return closeAmount;
else
return 0;
}
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
if (marginAmountBeforeClose == 0) {
marginAmountBeforeClose = _getCurrentMarginAmount(
loanOrder,
loanPosition,
oracleAddress
);
if (ensureHealthy && marginAmountBeforeClose <= loanOrder.maintenanceMarginAmount) {
revert("BZxLoanHealth::_closeLoanPartially: unhealthy position");
}
if (loanOrder.loanTokenAddress == loanPosition.collateralTokenAddressFilled) {
collateralCloseAmount = closeAmount;
} else {
// variables needed later are re-purposed here; variable names are inappropriate
(destTokenAmountReceived, sourceTokenAmountUsed,) = OracleInterface(oracleAddress).getTradeData(
loanOrder.loanTokenAddress,
loanPosition.collateralTokenAddressFilled,
MAX_UINT // get best rate
);
collateralCloseAmount = closeAmount
.mul(destTokenAmountReceived); // sourceToDestRate
collateralCloseAmount = collateralCloseAmount
.div(sourceTokenAmountUsed); // sourceToDestPrecision
}
collateralCloseAmount = collateralCloseAmount
.mul(marginAmountBeforeClose);
collateralCloseAmount = collateralCloseAmount
.div(10**20);
}
uint256 closeAmountNotRecovered = closeAmount;
// pay lender interest so far, and do partial interest refund to trader
if (loanOrder.interestAmount != 0) {
(destTokenAmountReceived, sourceTokenAmountUsed) = _settleInterest(
loanOrder,
loanPosition,
closeAmount,
true, // sendToOracle
true // interestToCollateralSwap
);
if (destTokenAmountReceived != 0) {
closeAmountNotRecovered = closeAmountNotRecovered
.sub(destTokenAmountReceived);
//closeAmount = closeAmount
// .sub(destTokenAmountReceived);
collateralCloseAmount = collateralCloseAmount
.sub(sourceTokenAmountUsed);
/*(closeAmount, collateralCloseAmount) = _updateCloseAmounts(
closeAmount,
collateralCloseAmount,
destTokenAmountReceived
);*/
/*closeAmount = closeAmount
.sub(destTokenAmountReceived);
sourceTokenAmountUsed = sourceTokenAmountUsed
.mul(10**20);
sourceTokenAmountUsed = sourceTokenAmountUsed
.div(marginAmountBeforeClose);
if (collateralCloseAmount > sourceTokenAmountUsed) {
collateralCloseAmount = collateralCloseAmount
.sub(sourceTokenAmountUsed);
} else {
collateralCloseAmount = 0;
}*/
}
}
if (loanPosition.positionTokenAddressFilled != loanOrder.loanTokenAddress) {
if (loanPosition.positionTokenAmountFilled != 0) {
if (closeAmountNotRecovered != 0) {
(destTokenAmountReceived, sourceTokenAmountUsed) = _tradeWithOracle(
loanPosition.positionTokenAddressFilled,
loanOrder.loanTokenAddress,
oracleAddress,
loanPosition.positionTokenAmountFilled,
closeAmountNotRecovered // maxDestTokenAmount
);
if (destTokenAmountReceived < closeAmountNotRecovered) {
closeAmountNotRecovered = closeAmountNotRecovered - destTokenAmountReceived;
} else {
closeAmountNotRecovered = 0;
}
loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(sourceTokenAmountUsed);
}
}
} else {
if (loanPosition.positionTokenAmountFilled < closeAmountNotRecovered) {
closeAmountNotRecovered = closeAmountNotRecovered - loanPosition.positionTokenAmountFilled;
loanPosition.positionTokenAmountFilled = 0;
} else {
// we can close all of closeAmountNotRecovered, if here
closeAmountNotRecovered = 0;
loanPosition.positionTokenAmountFilled = loanPosition.positionTokenAmountFilled.sub(closeAmount);
}
}
if (marginAmountBeforeClose > loanOrder.maintenanceMarginAmount) {
// only use collateral if the position doesn't need liquidation
if (loanPosition.collateralTokenAmountFilled != 0) {
//sourceTokenAmountUsed = 0;
if (closeAmountNotRecovered != 0) {
// try to recover closeAmount needed from collateral
if (loanPosition.collateralTokenAddressFilled != loanOrder.loanTokenAddress) {
(destTokenAmountReceived, sourceTokenAmountUsed) = _tradeWithOracle(
loanPosition.collateralTokenAddressFilled,
loanOrder.loanTokenAddress,
oracleAddress,
loanPosition.collateralTokenAmountFilled,
closeAmountNotRecovered // maxDestTokenAmount
);
//closeAmountNotRecovered = closeAmountNotRecovered.sub(destTokenAmountReceived);
/*loanPosition.collateralTokenAmountFilled = loanPosition.collateralTokenAmountFilled.sub(sourceTokenAmountUsed);
if (closeAmountNotRecovered != 0) {
// we've closed as much as we can
closeAmount = closeAmount.sub(closeAmountNotRecovered);
}*/
// older code
if (destTokenAmountReceived < closeAmountNotRecovered) {
// update collateralCloseAmount and closeAmount for the actual amount we will be able to close
closeAmountNotRecovered = closeAmountNotRecovered.sub(destTokenAmountReceived);
(closeAmount, collateralCloseAmount) = _updateCloseAmounts(
closeAmount,
collateralCloseAmount,
closeAmountNotRecovered
);
}
loanPosition.collateralTokenAmountFilled = loanPosition.collateralTokenAmountFilled.sub(sourceTokenAmountUsed);
} else {
if (loanPosition.collateralTokenAmountFilled < closeAmountNotRecovered) {
// update collateralCloseAmount and closeAmount for the actual amount we will be able to close
// older code
(closeAmount, collateralCloseAmount) = _updateCloseAmounts(
closeAmount,
collateralCloseAmount,
loanPosition.collateralTokenAmountFilled
);
//sourceTokenAmountUsed = loanPosition.collateralTokenAmountFilled;
//closeAmountNotRecovered = closeAmountNotRecovered.sub(loanPosition.collateralTokenAmountFilled);
loanPosition.collateralTokenAmountFilled = 0;
// we've closed as much as we can (newer code)
//closeAmount = closeAmount.sub(closeAmountNotRecovered);
} else {
// we can close all of closeAmount, if here
//sourceTokenAmountUsed = closeAmountNotRecovered;
//closeAmountNotRecovered = 0;
loanPosition.collateralTokenAmountFilled = loanPosition.collateralTokenAmountFilled.sub(closeAmountNotRecovered);
}
}
}
if (collateralCloseAmount != 0 &&
loanPosition.collateralTokenAmountFilled >= collateralCloseAmount) {
// send excess collateral token back to the trader
if (!BZxVault(vaultContract).withdrawToken(
loanPosition.collateralTokenAddressFilled,
msg.sender,
collateralCloseAmount
)) {
revert("BZxLoanHealth::_closeLoanPartially: BZxVault.withdrawToken collateral failed");
}
loanPosition.collateralTokenAmountFilled = loanPosition.collateralTokenAmountFilled.sub(collateralCloseAmount);
}
}
} else {
closeAmount = closeAmount.sub(closeAmountNotRecovered);
}
require(closeAmount > 0, "closeAmount should not == 0");
loanPosition.loanTokenAmountFilled = loanPosition.loanTokenAmountFilled.sub(closeAmount);
//loanPosition.loanTokenAmountUsed = loanPosition.loanTokenAmountUsed.sub(closeAmount); <- not used yet
_settlePartialClosure(
loanOrder.loanOrderHash,
loanOrder.loanTokenAddress,
loanOrder.loanTokenAmount,
closeAmount
);
reentrancyLock = REENTRANCY_GUARD_FREE; // reentrancy safe at this point
if (!OracleInterface(oracleAddress).didCloseLoan(
loanOrder,
loanPosition,
msg.sender, // loanCloser
closeAmount,
false, // isLiquidation
gasUsed
)) {
revert("BZxLoanHealth::_closeLoanPartially: OracleInterface.didCloseLoan failed");
}
return closeAmount;
}
function _getCurrentMarginAmount(
LoanOrder memory loanOrder,
LoanPosition memory loanPosition,
address oracleAddress)
internal
view
returns (uint256)
{
return OracleInterface(oracleAddress).getCurrentMarginAmount(
loanOrder.loanTokenAddress,
loanPosition.positionTokenAddressFilled,
loanPosition.collateralTokenAddressFilled,
loanPosition.loanTokenAmountFilled,
loanPosition.positionTokenAmountFilled,
loanPosition.collateralTokenAmountFilled
);
}
function _tradeWithOracle(
address sourceTokenAddress,
address destTokenAddress,
address oracleAddress,
uint256 sourceTokenAmount,
uint256 maxDestTokenAmount)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed)
{
if (!BZxVault(vaultContract).withdrawToken(
sourceTokenAddress,
oracleAddress,
sourceTokenAmount
)) {
revert("oracletrade: withdrawToken (sourceToken) failed");
}
(destTokenAmountReceived, sourceTokenAmountUsed) = OracleInterface(oracleAddress).trade(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount,
maxDestTokenAmount
);
require (destTokenAmountReceived != 0, "destTokenAmountReceived == 0");
if (destTokenAmountReceived == MAX_UINT) {
destTokenAmountReceived = 0;
}
}
function _settlePartialClosure(
bytes32 loanOrderHash,
address loanTokenAddress,
uint256 loanTokenAmount,
uint256 closeAmount)
internal
{
// send closed token back to the lender
if (!BZxVault(vaultContract).withdrawToken(
loanTokenAddress,
orderLender[loanOrderHash],
closeAmount
)) {
revert("BZxLoanHealth::_closeLoanPartially: BZxVault.withdrawToken loan failed");
}
if (orderAux[loanOrderHash].expirationUnixTimestampSec == 0 || block.timestamp < orderAux[loanOrderHash].expirationUnixTimestampSec) {
// since order is not expired, we make the closeAmount available for borrowing again
orderFilledAmounts[loanOrderHash] = orderFilledAmounts[loanOrderHash].sub(closeAmount);
if (!orderListIndex[loanOrderHash][address(0)].isSet && loanTokenAmount.sub(_getUnavailableLoanTokenAmount(loanOrderHash)) > 0) {
// record of fillable (non-expired/unfilled) orders
orderList[address(0)].push(loanOrderHash);
orderListIndex[loanOrderHash][address(0)] = ListIndex({
index: orderList[address(0)].length-1,
isSet: true
});
}
}
}
function _updateCloseAmounts(
uint256 closeAmount,
uint256 collateralCloseAmount,
uint256 subtrahend)
internal
pure
returns (uint256, uint256)
{
uint256 newCloseAmount = closeAmount
.sub(subtrahend);
return (
newCloseAmount,
collateralCloseAmount
.mul(newCloseAmount)
.div(closeAmount)
);
}
}
| Called by the trader to close part of their loan early. loanOrderHash A unique hash representing the loan order closeAmount The amount of the loan token to return to the lender return The actual amount closed. Greater than closeAmount means the loan needed liquidation. | function closeLoanPartially(
bytes32 loanOrderHash,
uint256 closeAmount)
external
nonReentrant
tracksGas
returns (uint256 actualCloseAmount)
{
if (closeAmount == 0) {
return 0;
}
LoanPosition storage loanPosition = loanPositions[loanPositionsIds[loanOrderHash][msg.sender]];
if (loanPosition.loanTokenAmountFilled == 0 || !loanPosition.active) {
return 0;
}
LoanOrder memory loanOrder = orders[loanOrderHash];
if (loanOrder.loanTokenAddress == address(0)) {
revert("_closeLoanPartially: loanOrder.loanTokenAddress == address(0)");
}
return _closeLoanPartially(
loanOrder,
loanPosition,
closeAmount,
oracleAddresses[loanOrder.oracleAddress],
);
}
| 882,118 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/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: contracts/interface/IBasicMultiToken.sol
contract IBasicMultiToken is ERC20 {
event Bundle(address indexed who, address indexed beneficiary, uint256 value);
event Unbundle(address indexed who, address indexed beneficiary, uint256 value);
ERC20[] public tokens;
function tokensCount() public view returns(uint256);
function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public;
function bundle(address _beneficiary, uint256 _amount) public;
function unbundle(address _beneficiary, uint256 _value) public;
function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public;
function disableBundling() public;
function enableBundling() public;
}
// File: contracts/interface/IMultiToken.sol
contract IMultiToken is IBasicMultiToken {
event Update();
event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return);
mapping(address => uint256) public weights;
function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount);
function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount);
function disableChanges() public;
}
// File: contracts/ext/CheckedERC20.sol
library CheckedERC20 {
using SafeMath for uint;
function isContract(address addr) internal view returns(bool result) {
// solium-disable-next-line security/no-inline-assembly
assembly {
result := gt(extcodesize(addr), 0)
}
}
function handleReturnBool() internal pure returns(bool result) {
// solium-disable-next-line security/no-inline-assembly
assembly {
switch returndatasize()
case 0 { // not a std erc20
result := 1
}
case 32 { // std erc20
returndatacopy(0, 0, 32)
result := mload(0)
}
default { // anything else, should revert for safety
revert(0, 0)
}
}
}
function handleReturnBytes32() internal pure returns(bytes32 result) {
// solium-disable-next-line security/no-inline-assembly
assembly {
if eq(returndatasize(), 32) { // not a std erc20
returndatacopy(0, 0, 32)
result := mload(0)
}
if gt(returndatasize(), 32) { // std erc20
returndatacopy(0, 64, 32)
result := mload(0)
}
if lt(returndatasize(), 32) { // anything else, should revert for safety
revert(0, 0)
}
}
}
function asmTransfer(address _token, address _to, uint256 _value) internal returns(bool) {
require(isContract(_token));
// solium-disable-next-line security/no-low-level-calls
require(_token.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value));
return handleReturnBool();
}
function asmTransferFrom(address _token, address _from, address _to, uint256 _value) internal returns(bool) {
require(isContract(_token));
// solium-disable-next-line security/no-low-level-calls
require(_token.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value));
return handleReturnBool();
}
function asmApprove(address _token, address _spender, uint256 _value) internal returns(bool) {
require(isContract(_token));
// solium-disable-next-line security/no-low-level-calls
require(_token.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value));
return handleReturnBool();
}
//
function checkedTransfer(ERC20 _token, address _to, uint256 _value) internal {
if (_value > 0) {
uint256 balance = _token.balanceOf(this);
asmTransfer(_token, _to, _value);
require(_token.balanceOf(this) == balance.sub(_value), "checkedTransfer: Final balance didn't match");
}
}
function checkedTransferFrom(ERC20 _token, address _from, address _to, uint256 _value) internal {
if (_value > 0) {
uint256 toBalance = _token.balanceOf(_to);
asmTransferFrom(_token, _from, _to, _value);
require(_token.balanceOf(_to) == toBalance.add(_value), "checkedTransfer: Final balance didn't match");
}
}
//
function asmName(address _token) internal view returns(bytes32) {
require(isContract(_token));
// solium-disable-next-line security/no-low-level-calls
require(_token.call(bytes4(keccak256("name()"))));
return handleReturnBytes32();
}
function asmSymbol(address _token) internal view returns(bytes32) {
require(isContract(_token));
// solium-disable-next-line security/no-low-level-calls
require(_token.call(bytes4(keccak256("symbol()"))));
return handleReturnBytes32();
}
}
// 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/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: contracts/registry/MultiChanger.sol
contract IEtherToken is ERC20 {
function deposit() public payable;
function withdraw(uint256 _amount) public;
}
contract IBancorNetwork {
function convert(
address[] _path,
uint256 _amount,
uint256 _minReturn
)
public
payable
returns(uint256);
function claimAndConvert(
address[] _path,
uint256 _amount,
uint256 _minReturn
)
public
payable
returns(uint256);
}
contract IKyberNetworkProxy {
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint);
}
contract MultiChanger is CanReclaimToken {
using SafeMath for uint256;
using CheckedERC20 for ERC20;
// Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function externalCall(address destination, uint value, bytes data, uint dataOffset, uint dataLength) internal returns (bool result) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
add(d, dataOffset),
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
}
function change(
bytes _callDatas,
uint[] _starts // including 0 and LENGTH values
)
internal
{
for (uint i = 0; i < _starts.length - 1; i++) {
require(externalCall(this, 0, _callDatas, _starts[i], _starts[i + 1] - _starts[i]));
}
}
function sendEthValue(address _target, bytes _data, uint256 _value) external {
// solium-disable-next-line security/no-call-value
require(_target.call.value(_value)(_data));
}
function sendEthProportion(address _target, bytes _data, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
// solium-disable-next-line security/no-call-value
require(_target.call.value(value)(_data));
}
function approveTokenAmount(address _target, bytes _data, ERC20 _fromToken, uint256 _amount) external {
if (_fromToken.allowance(this, _target) != 0) {
_fromToken.asmApprove(_target, 0);
}
_fromToken.asmApprove(_target, _amount);
// solium-disable-next-line security/no-low-level-calls
require(_target.call(_data));
}
function approveTokenProportion(address _target, bytes _data, ERC20 _fromToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
if (_fromToken.allowance(this, _target) != 0) {
_fromToken.asmApprove(_target, 0);
}
_fromToken.asmApprove(_target, amount);
// solium-disable-next-line security/no-low-level-calls
require(_target.call(_data));
}
function transferTokenAmount(address _target, bytes _data, ERC20 _fromToken, uint256 _amount) external {
_fromToken.asmTransfer(_target, _amount);
// solium-disable-next-line security/no-low-level-calls
require(_target.call(_data));
}
function transferTokenProportion(address _target, bytes _data, ERC20 _fromToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
_fromToken.asmTransfer(_target, amount);
// solium-disable-next-line security/no-low-level-calls
require(_target.call(_data));
}
// Ether token
function withdrawEtherTokenAmount(IEtherToken _etherToken, uint256 _amount) external {
_etherToken.withdraw(_amount);
}
function withdrawEtherTokenProportion(IEtherToken _etherToken, uint256 _mul, uint256 _div) external {
uint256 amount = _etherToken.balanceOf(this).mul(_mul).div(_div);
_etherToken.withdraw(amount);
}
// Bancor Network
function bancorSendEthValue(IBancorNetwork _bancor, address[] _path, uint256 _value) external {
_bancor.convert.value(_value)(_path, _value, 1);
}
function bancorSendEthProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
_bancor.convert.value(value)(_path, value, 1);
}
function bancorApproveTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
if (ERC20(_path[0]).allowance(this, _bancor) == 0) {
ERC20(_path[0]).asmApprove(_bancor, uint256(-1));
}
_bancor.claimAndConvert(_path, _amount, 1);
}
function bancorApproveTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(this).mul(_mul).div(_div);
if (ERC20(_path[0]).allowance(this, _bancor) == 0) {
ERC20(_path[0]).asmApprove(_bancor, uint256(-1));
}
_bancor.claimAndConvert(_path, amount, 1);
}
function bancorTransferTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
ERC20(_path[0]).asmTransfer(_bancor, _amount);
_bancor.convert(_path, _amount, 1);
}
function bancorTransferTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(this).mul(_mul).div(_div);
ERC20(_path[0]).asmTransfer(_bancor, amount);
_bancor.convert(_path, amount, 1);
}
function bancorAlreadyTransferedTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
_bancor.convert(_path, _amount, 1);
}
function bancorAlreadyTransferedTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(_bancor).mul(_mul).div(_div);
_bancor.convert(_path, amount, 1);
}
// Kyber Network
function kyberSendEthProportion(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
_kyber.trade.value(value)(
_fromToken,
value,
_toToken,
this,
1 << 255,
0,
0
);
}
function kyberApproveTokenAmount(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _amount) external {
if (_fromToken.allowance(this, _kyber) == 0) {
_fromToken.asmApprove(_kyber, uint256(-1));
}
_kyber.trade(
_fromToken,
_amount,
_toToken,
this,
1 << 255,
0,
0
);
}
function kyberApproveTokenProportion(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
this.kyberApproveTokenAmount(_kyber, _fromToken, _toToken, amount);
}
}
// File: contracts/registry/MultiSeller.sol
contract MultiSeller is MultiChanger {
using CheckedERC20 for ERC20;
using CheckedERC20 for IMultiToken;
function() public payable {
// solium-disable-next-line security/no-tx-origin
require(tx.origin != msg.sender);
}
function sellForOrigin(
IMultiToken _mtkn,
uint256 _amount,
bytes _callDatas,
uint[] _starts // including 0 and LENGTH values
)
public
{
sell(
_mtkn,
_amount,
_callDatas,
_starts,
tx.origin // solium-disable-line security/no-tx-origin
);
}
function sell(
IMultiToken _mtkn,
uint256 _amount,
bytes _callDatas,
uint[] _starts, // including 0 and LENGTH values
address _for
)
public
{
_mtkn.asmTransferFrom(msg.sender, this, _amount);
_mtkn.unbundle(this, _amount);
change(_callDatas, _starts);
_for.transfer(address(this).balance);
}
// DEPRECATED:
function sellOnApproveForOrigin(
IMultiToken _mtkn,
uint256 _amount,
ERC20 _throughToken,
address[] _exchanges,
bytes _datas,
uint[] _datasIndexes // including 0 and LENGTH values
)
public
{
sellOnApprove(
_mtkn,
_amount,
_throughToken,
_exchanges,
_datas,
_datasIndexes,
tx.origin
);
}
function sellOnApprove(
IMultiToken _mtkn,
uint256 _amount,
ERC20 _throughToken,
address[] _exchanges,
bytes _datas,
uint[] _datasIndexes, // including 0 and LENGTH values
address _for
)
public
{
if (_throughToken == address(0)) {
require(_mtkn.tokensCount() == _exchanges.length, "sell: _mtkn should have the same tokens count as _exchanges");
} else {
require(_mtkn.tokensCount() + 1 == _exchanges.length, "sell: _mtkn should have tokens count + 1 equal _exchanges length");
}
require(_datasIndexes.length == _exchanges.length + 1, "sell: _datasIndexes should start with 0 and end with LENGTH");
_mtkn.transferFrom(msg.sender, this, _amount);
_mtkn.unbundle(this, _amount);
for (uint i = 0; i < _exchanges.length; i++) {
bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]);
for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) {
data[j - _datasIndexes[i]] = _datas[j];
}
if (data.length == 0) {
continue;
}
if (i == _exchanges.length - 1 && _throughToken != address(0)) {
if (_throughToken.allowance(this, _exchanges[i]) == 0) {
_throughToken.asmApprove(_exchanges[i], uint256(-1));
}
} else {
ERC20 token = _mtkn.tokens(i);
if (_exchanges[i] == 0) {
token.asmTransfer(_for, token.balanceOf(this));
continue;
}
token.asmApprove(_exchanges[i], token.balanceOf(this));
}
require(_exchanges[i].call(data), "sell: exchange arbitrary call failed");
}
_for.transfer(address(this).balance);
if (_throughToken != address(0) && _throughToken.balanceOf(this) > 0) {
_throughToken.asmTransfer(_for, _throughToken.balanceOf(this));
}
}
} | solium-disable-next-line security/no-tx-origin | function() public payable {
require(tx.origin != msg.sender);
}
| 1,425,293 |
pragma solidity 0.6.12;
interface IAdmin {
function isAdmin(address user) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/ISalesFactory.sol
pragma solidity 0.6.12;
interface ISalesFactory {
function setSaleOwnerAndToken(address saleOwner, address saleToken) external;
function isSaleCreatedThroughFactory(address sale) external view returns (bool);
}
// File contracts/interfaces/IAllocationStaking.sol
pragma solidity 0.6.12;
interface IAllocationStaking {
function redistributeFame(uint256 _pid, address _user, uint256 _amountToBurn) external;
function deposited(uint256 _pid, address _user) external view returns (uint256);
function setTokensUnlockTime(uint256 _pid, address _user, uint256 _tokensUnlockTime) external;
}
// File contracts/sales/FantomSale.sol
pragma solidity 0.6.12;
contract FantomSale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Pointer to Allocation staking contract, where burnFameFromUser will be called.
IAllocationStaking public allocationStakingContract;
// Pointer to sales factory contract
ISalesFactory public factory;
// Admin contract
IAdmin public admin;
struct Sale {
// Token being sold
IERC20 token;
// Is sale created
bool isCreated;
// Are earnings withdrawn
bool earningsWithdrawn;
// Is leftover withdrawn
bool leftoverWithdrawn;
// Have tokens been deposited
bool tokensDeposited;
// Address of sale owner
address saleOwner;
// Price of the token quoted in FTM
uint256 tokenPriceInFTM;
// Amount of tokens to sell
uint256 amountOfTokensToSell;
// Total tokens being sold
uint256 totalTokensSold;
// Total FTM Raised
uint256 totalFTMRaised;
// Sale end time
uint256 saleEnd;
// When tokens can be withdrawn
uint256 tokensUnlockTime;
}
// Participation structure
struct Participation {
uint256 amountBought;
uint256 amountFTMPaid;
uint256 timeParticipated;
uint256 roundId;
bool[] isPortionWithdrawn;
}
// Round structure
struct Round {
uint256 startTime;
uint256 maxParticipation;
}
struct Registration {
uint256 registrationTimeStarts;
uint256 registrationTimeEnds;
uint256 numberOfRegistrants;
}
// Sale
Sale public sale;
// Registration
Registration public registration;
// Number of users participated in the sale.
uint256 public numberOfParticipants;
// Array storing IDS of rounds (IDs start from 1, so they can't be mapped as array indexes
uint256[] public roundIds;
// Mapping round Id to round
mapping(uint256 => Round) public roundIdToRound;
// Mapping user to his participation
mapping(address => Participation) public userToParticipation;
// User to round for which he registered
mapping(address => uint256) public addressToRoundRegisteredFor;
// mapping if user is participated or not
mapping(address => bool) public isParticipated;
// wei precision
uint256 public constant one = 10**18;
// Times when portions are getting unlocked
uint256[] public vestingPortionsUnlockTime;
// Percent of the participation user can withdraw
uint256[] public vestingPercentPerPortion;
//Precision for percent for portion vesting
uint256 public portionVestingPrecision;
// Added configurable round ID for staking round
uint256 public stakingRoundId;
// Max vesting time shift
uint256 public maxVestingTimeShift;
// Registration deposit FTM, which will be paid during the registration, and returned back during the participation.
uint256 public registrationDepositFTM;
// Accounting total FTM collected, after sale admin can withdraw this
uint256 public registrationFees;
// Restricting calls only to sale owner
modifier onlySaleOwner() {
require(msg.sender == sale.saleOwner, "OnlySaleOwner:: Restricted");
_;
}
modifier onlyAdmin() {
require(
admin.isAdmin(msg.sender),
"Only admin can call this function."
);
_;
}
// EVENTS
event TokensSold(address user, uint256 amount);
event UserRegistered(address user, uint256 roundId);
event TokenPriceSet(uint256 newPrice);
event MaxParticipationSet(uint256 roundId, uint256 maxParticipation);
event TokensWithdrawn(address user, uint256 amount);
event SaleCreated(
address saleOwner,
uint256 tokenPriceInFTM,
uint256 amountOfTokensToSell,
uint256 saleEnd,
uint256 tokensUnlockTime
);
event RegistrationTimeSet(
uint256 registrationTimeStarts,
uint256 registrationTimeEnds
);
event RoundAdded(
uint256 roundId,
uint256 startTime,
uint256 maxParticipation
);
event RegistrationFTMRefunded(address user, uint256 amountRefunded);
// Constructor, always initialized through SalesFactory
constructor(address _admin, address _allocationStaking) public {
require(_admin != address(0));
require(_allocationStaking != address(0));
admin = IAdmin(_admin);
factory = ISalesFactory(msg.sender);
allocationStakingContract = IAllocationStaking(_allocationStaking);
}
/// @notice Function to set vesting params
function setVestingParams(
uint256[] memory _unlockingTimes,
uint256[] memory _percents,
uint256 _maxVestingTimeShift
) external onlyAdmin {
require(
vestingPercentPerPortion.length == 0 &&
vestingPortionsUnlockTime.length == 0
);
require(_unlockingTimes.length == _percents.length);
require(portionVestingPrecision > 0, "Safeguard for making sure setSaleParams get first called.");
require(_maxVestingTimeShift <= 30 days, "Maximal shift is 30 days.");
// Set max vesting time shift
maxVestingTimeShift = _maxVestingTimeShift;
uint256 sum;
for (uint256 i = 0; i < _unlockingTimes.length; i++) {
vestingPortionsUnlockTime.push(_unlockingTimes[i]);
vestingPercentPerPortion.push(_percents[i]);
sum += _percents[i];
}
require(sum == portionVestingPrecision, "Percent distribution issue.");
}
function shiftVestingUnlockingTimes(uint256 timeToShift)
external
onlyAdmin
{
require(
timeToShift > 0 && timeToShift < maxVestingTimeShift,
"Shift must be nonzero and smaller than maxVestingTimeShift."
);
// Time can be shifted only once.
maxVestingTimeShift = 0;
for (uint256 i = 0; i < vestingPortionsUnlockTime.length; i++) {
vestingPortionsUnlockTime[i] = vestingPortionsUnlockTime[i].add(
timeToShift
);
}
}
/// @notice Admin function to set sale parameters
function setSaleParams(
address _token,
address _saleOwner,
uint256 _tokenPriceInFTM,
uint256 _amountOfTokensToSell,
uint256 _saleEnd,
uint256 _tokensUnlockTime,
uint256 _portionVestingPrecision,
uint256 _stakingRoundId,
uint256 _registrationDepositFTM
) external onlyAdmin {
require(!sale.isCreated, "setSaleParams: Sale is already created.");
require(
_saleOwner != address(0),
"setSaleParams: Sale owner address can not be 0."
);
require(
_tokenPriceInFTM != 0 &&
_amountOfTokensToSell != 0 &&
_saleEnd > block.timestamp &&
_tokensUnlockTime > block.timestamp,
"setSaleParams: Bad input"
);
require(_portionVestingPrecision >= 100, "Should be at least 100");
require(_stakingRoundId > 0, "Staking round ID can not be 0.");
// Set params
sale.token = IERC20(_token);
sale.isCreated = true;
sale.saleOwner = _saleOwner;
sale.tokenPriceInFTM = _tokenPriceInFTM;
sale.amountOfTokensToSell = _amountOfTokensToSell;
sale.saleEnd = _saleEnd;
sale.tokensUnlockTime = _tokensUnlockTime;
// Deposit in FTM, sent during the registration
registrationDepositFTM = _registrationDepositFTM;
// Set portion vesting precision
portionVestingPrecision = _portionVestingPrecision;
// Set staking round id
stakingRoundId = _stakingRoundId;
// Emit event
emit SaleCreated(
sale.saleOwner,
sale.tokenPriceInFTM,
sale.amountOfTokensToSell,
sale.saleEnd,
sale.tokensUnlockTime
);
}
// @notice Function to retroactively set sale token address, can be called only once,
// after initial contract creation has passed. Added as an options for teams which
// are not having token at the moment of sale launch.
function setSaleToken(
address saleToken
)
external
onlyAdmin
{
require(address(sale.token) == address(0));
sale.token = IERC20(saleToken);
}
/// @notice Function to set registration period parameters
function setRegistrationTime(
uint256 _registrationTimeStarts,
uint256 _registrationTimeEnds
) external onlyAdmin {
require(sale.isCreated);
require(registration.registrationTimeStarts == 0);
require(
_registrationTimeStarts >= block.timestamp &&
_registrationTimeEnds > _registrationTimeStarts
);
require(_registrationTimeEnds < sale.saleEnd);
if (roundIds.length > 0) {
require(
_registrationTimeEnds < roundIdToRound[roundIds[0]].startTime
);
}
registration.registrationTimeStarts = _registrationTimeStarts;
registration.registrationTimeEnds = _registrationTimeEnds;
emit RegistrationTimeSet(
registration.registrationTimeStarts,
registration.registrationTimeEnds
);
}
function setRounds(
uint256[] calldata startTimes,
uint256[] calldata maxParticipations
) external onlyAdmin {
require(sale.isCreated);
require(
startTimes.length == maxParticipations.length,
"setRounds: Bad input."
);
require(roundIds.length == 0, "setRounds: Rounds are set already.");
require(startTimes.length > 0);
uint256 lastTimestamp = 0;
for (uint256 i = 0; i < startTimes.length; i++) {
require(startTimes[i] > registration.registrationTimeEnds);
require(startTimes[i] < sale.saleEnd);
require(startTimes[i] >= block.timestamp);
require(maxParticipations[i] > 0);
require(startTimes[i] > lastTimestamp);
lastTimestamp = startTimes[i];
// Compute round Id
uint256 roundId = i + 1;
// Push id to array of ids
roundIds.push(roundId);
// Create round
Round memory round = Round(startTimes[i], maxParticipations[i]);
// Map round id to round
roundIdToRound[roundId] = round;
// Fire event
emit RoundAdded(roundId, round.startTime, round.maxParticipation);
}
}
/// @notice Registration for sale.
/// @param roundId is the round for which user expressed interest to participate
function registerForSale(uint256 roundId)
external
payable
{
require(
msg.value == registrationDepositFTM,
"Registration deposit does not match."
);
require(roundId != 0, "Round ID can not be 0.");
require(roundId <= roundIds.length, "Invalid round id");
require(
block.timestamp >= registration.registrationTimeStarts &&
block.timestamp <= registration.registrationTimeEnds,
"Registration gate is closed."
);
require(
addressToRoundRegisteredFor[msg.sender] == 0,
"User can not register twice."
);
// Rounds are 1,2,3
addressToRoundRegisteredFor[msg.sender] = roundId;
// Special cases for staking round
if (roundId == stakingRoundId) {
// Lock users stake
allocationStakingContract.setTokensUnlockTime(
0,
msg.sender,
sale.saleEnd
);
}
// Increment number of registered users
registration.numberOfRegistrants++;
// Increase earnings from registration fees
registrationFees = registrationFees.add(msg.value);
// Emit Registration event
emit UserRegistered(msg.sender, roundId);
}
/// @notice Admin function, to update token price before sale to match the closest $ desired rate.
/// @dev This will be updated with an oracle during the sale every N minutes, so the users will always
/// pay initialy set $ value of the token. This is to reduce reliance on the FTM volatility.
function updateTokenPriceInFTM(uint256 price) external onlyAdmin {
require(price > 0, "Price can not be 0.");
// Allowing oracle to run and change the sale value
sale.tokenPriceInFTM = price;
emit TokenPriceSet(price);
}
/// @notice Admin function to postpone the sale
function postponeSale(uint256 timeToShift) external onlyAdmin {
require(
block.timestamp < roundIdToRound[roundIds[0]].startTime,
"1st round already started."
);
// Iterate through all registered rounds and postpone them
for (uint256 i = 0; i < roundIds.length; i++) {
Round storage round = roundIdToRound[roundIds[i]];
// Postpone sale
round.startTime = round.startTime.add(timeToShift);
require(
round.startTime + timeToShift < sale.saleEnd,
"Start time can not be greater than end time."
);
}
}
/// @notice Function to extend registration period
function extendRegistrationPeriod(uint256 timeToAdd) external onlyAdmin {
require(
registration.registrationTimeEnds.add(timeToAdd) <
roundIdToRound[roundIds[0]].startTime,
"Registration period overflows sale start."
);
registration.registrationTimeEnds = registration
.registrationTimeEnds
.add(timeToAdd);
}
/// @notice Admin function to set max participation cap per round
function setCapPerRound(uint256[] calldata rounds, uint256[] calldata caps)
external
onlyAdmin
{
require(
block.timestamp < roundIdToRound[roundIds[0]].startTime,
"1st round already started."
);
require(rounds.length == caps.length, "Arrays length is different.");
for (uint256 i = 0; i < rounds.length; i++) {
require(caps[i] > 0, "Can't set max participation to 0");
Round storage round = roundIdToRound[rounds[i]];
round.maxParticipation = caps[i];
emit MaxParticipationSet(rounds[i], round.maxParticipation);
}
}
// Function for owner to deposit tokens, can be called only once.
function depositTokens() external onlySaleOwner {
require(
!sale.tokensDeposited, "Deposit can be done only once"
);
sale.tokensDeposited = true;
sale.token.safeTransferFrom(
msg.sender,
address(this),
sale.amountOfTokensToSell
);
}
// Function to participate in the sales
function participate(
uint256 amount,
uint256 amountFameToBurn,
uint256 roundId
) external payable {
require(roundId != 0, "Round can not be 0.");
require(
amount <= roundIdToRound[roundId].maxParticipation,
"Overflowing maximal participation for this round."
);
// User must have registered for the round in advance
require(
addressToRoundRegisteredFor[msg.sender] == roundId,
"Not registered for this round"
);
// Check user haven't participated before
require(!isParticipated[msg.sender], "User can participate only once.");
// Disallow contract calls.
require(msg.sender == tx.origin, "Only direct contract calls.");
// Get current active round
uint256 currentRound = getCurrentRound();
// Assert that
require(
roundId == currentRound,
"You can not participate in this round."
);
// Compute the amount of tokens user is buying
uint256 amountOfTokensBuying = (msg.value).mul(one).div(
sale.tokenPriceInFTM
);
// Must buy more than 0 tokens
require(amountOfTokensBuying > 0, "Can't buy 0 tokens");
// Check in terms of user allo
require(
amountOfTokensBuying <= amount,
"Trying to buy more than allowed."
);
// Increase amount of sold tokens
sale.totalTokensSold = sale.totalTokensSold.add(amountOfTokensBuying);
// Increase amount of FTM raised
sale.totalFTMRaised = sale.totalFTMRaised.add(msg.value);
bool[] memory _isPortionWithdrawn = new bool[](
vestingPortionsUnlockTime.length
);
// Create participation object
Participation memory p = Participation({
amountBought: amountOfTokensBuying,
amountFTMPaid: msg.value,
timeParticipated: block.timestamp,
roundId: roundId,
isPortionWithdrawn: _isPortionWithdrawn
});
// Staking round only.
if (roundId == stakingRoundId) {
// Burn FAME from this user.
allocationStakingContract.redistributeFame(
0,
msg.sender,
amountFameToBurn
);
}
// Add participation for user.
userToParticipation[msg.sender] = p;
// Mark user is participated
isParticipated[msg.sender] = true;
// Increment number of participants in the Sale.
numberOfParticipants++;
// Decrease of available registration fees
registrationFees = registrationFees.sub(registrationDepositFTM);
// Transfer registration deposit amount in FTM back to the users.
safeTransferFTM(msg.sender, registrationDepositFTM);
emit RegistrationFTMRefunded(msg.sender, registrationDepositFTM);
emit TokensSold(msg.sender, amountOfTokensBuying);
}
/// Users can claim their participation
function withdrawTokens(uint256 portionId) external {
require(
block.timestamp >= sale.tokensUnlockTime,
"Tokens can not be withdrawn yet."
);
require(portionId < vestingPercentPerPortion.length);
Participation storage p = userToParticipation[msg.sender];
if (
!p.isPortionWithdrawn[portionId] &&
vestingPortionsUnlockTime[portionId] <= block.timestamp
) {
p.isPortionWithdrawn[portionId] = true;
uint256 amountWithdrawing = p
.amountBought
.mul(vestingPercentPerPortion[portionId])
.div(portionVestingPrecision);
// Withdraw percent which is unlocked at that portion
if(amountWithdrawing > 0) {
sale.token.safeTransfer(msg.sender, amountWithdrawing);
emit TokensWithdrawn(msg.sender, amountWithdrawing);
}
} else {
revert("Tokens already withdrawn or portion not unlocked yet.");
}
}
// Expose function where user can withdraw multiple unlocked portions at once.
function withdrawMultiplePortions(uint256 [] calldata portionIds) external {
uint256 totalToWithdraw = 0;
Participation storage p = userToParticipation[msg.sender];
for(uint i=0; i < portionIds.length; i++) {
uint256 portionId = portionIds[i];
require(portionId < vestingPercentPerPortion.length);
if (
!p.isPortionWithdrawn[portionId] &&
vestingPortionsUnlockTime[portionId] <= block.timestamp
) {
p.isPortionWithdrawn[portionId] = true;
uint256 amountWithdrawing = p
.amountBought
.mul(vestingPercentPerPortion[portionId])
.div(portionVestingPrecision);
// Withdraw percent which is unlocked at that portion
totalToWithdraw = totalToWithdraw.add(amountWithdrawing);
}
}
if(totalToWithdraw > 0) {
sale.token.safeTransfer(msg.sender, totalToWithdraw);
emit TokensWithdrawn(msg.sender, totalToWithdraw);
}
}
// Internal function to handle safe transfer
function safeTransferFTM(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success);
}
/// Function to withdraw all the earnings and the leftover of the sale contract.
function withdrawEarningsAndLeftover() external onlySaleOwner {
withdrawEarningsInternal();
withdrawLeftoverInternal();
}
// Function to withdraw only earnings
function withdrawEarnings() external onlySaleOwner {
withdrawEarningsInternal();
}
// Function to withdraw only leftover
function withdrawLeftover() external onlySaleOwner {
withdrawLeftoverInternal();
}
// function to withdraw earnings
function withdrawEarningsInternal() internal {
// Make sure sale ended
require(block.timestamp >= sale.saleEnd);
// Make sure owner can't withdraw twice
require(!sale.earningsWithdrawn);
sale.earningsWithdrawn = true;
// Earnings amount of the owner in FTM
uint256 totalProfit = sale.totalFTMRaised;
safeTransferFTM(msg.sender, totalProfit);
}
// Function to withdraw leftover
function withdrawLeftoverInternal() internal {
// Make sure sale ended
require(block.timestamp >= sale.saleEnd);
// Make sure owner can't withdraw twice
require(!sale.leftoverWithdrawn);
sale.leftoverWithdrawn = true;
// Amount of tokens which are not sold
uint256 leftover = sale.amountOfTokensToSell.sub(sale.totalTokensSold);
if (leftover > 0) {
sale.token.safeTransfer(msg.sender, leftover);
}
}
// Function after sale for admin to withdraw registration fees if there are any left.
function withdrawRegistrationFees() external onlyAdmin {
require(block.timestamp >= sale.saleEnd, "Require that sale has ended.");
require(registrationFees > 0, "No earnings from registration fees.");
// Transfer FTM to the admin wallet.
safeTransferFTM(msg.sender, registrationFees);
// Set registration fees to be 0
registrationFees = 0;
}
// Function where admin can withdraw all unused funds.
function withdrawUnusedFunds() external onlyAdmin {
uint256 balanceFTM = address(this).balance;
uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised;
safeTransferFTM(
msg.sender,
balanceFTM.sub(totalReservedForRaise.add(registrationFees))
);
}
// Function to act as a fallback and handle receiving FTM.
receive() external payable {
}
/// @notice Get current round in progress.
/// If 0 is returned, means sale didn't start or it's ended.
function getCurrentRound() public view returns (uint256) {
uint256 i = 0;
if (block.timestamp < roundIdToRound[roundIds[0]].startTime) {
return 0; // Sale didn't start yet.
}
while (
(i + 1) < roundIds.length &&
block.timestamp > roundIdToRound[roundIds[i + 1]].startTime
) {
i++;
}
if (block.timestamp >= sale.saleEnd) {
return 0; // Means sale is ended
}
return roundIds[i];
}
/// @notice Function to get participation for passed user address
function getParticipation(address _user)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
bool[] memory
)
{
Participation memory p = userToParticipation[_user];
return (
p.amountBought,
p.amountFTMPaid,
p.timeParticipated,
p.roundId,
p.isPortionWithdrawn
);
}
/// @notice Function to get number of registered users for sale
function getNumberOfRegisteredUsers() external view returns (uint256) {
return registration.numberOfRegistrants;
}
/// @notice Function to get all info about vesting.
function getVestingInfo()
external
view
returns (uint256[] memory, uint256[] memory)
{
return (vestingPortionsUnlockTime, vestingPercentPerPortion);
}
}
// File contracts/sales/SalesFactory.sol
pragma solidity 0.6.12;
contract SalesFactory {
IAdmin public admin;
address public allocationStaking;
mapping (address => bool) public isSaleCreatedThroughFactory;
mapping(address => address) public saleOwnerToSale;
mapping(address => address) public tokenToSale;
// Expose so query can be possible only by position as well
address [] public allSales;
event SaleDeployed(address saleContract);
event SaleOwnerAndTokenSetInFactory(address sale, address saleOwner, address saleToken);
modifier onlyAdmin {
require(admin.isAdmin(msg.sender), "Only Admin can deploy sales");
_;
}
constructor (address _adminContract, address _allocationStaking) public {
admin = IAdmin(_adminContract);
allocationStaking = _allocationStaking;
}
// Set allocation staking contract address.
function setAllocationStaking(address _allocationStaking) public onlyAdmin {
require(_allocationStaking != address(0));
allocationStaking = _allocationStaking;
}
function deploySale()
external
onlyAdmin
{
FantomSale sale = new FantomSale(address(admin), allocationStaking);
isSaleCreatedThroughFactory[address(sale)] = true;
allSales.push(address(sale));
emit SaleDeployed(address(sale));
}
// Function to return number of pools deployed
function getNumberOfSalesDeployed() external view returns (uint) {
return allSales.length;
}
// Function
function getLastDeployedSale() external view returns (address) {
//
if(allSales.length > 0) {
return allSales[allSales.length - 1];
}
return address(0);
}
// Function to get all sales
function getAllSales(uint startIndex, uint endIndex) external view returns (address[] memory) {
require(endIndex > startIndex, "Bad input");
address[] memory sales = new address[](endIndex - startIndex);
uint index = 0;
for(uint i = startIndex; i < endIndex; i++) {
sales[index] = allSales[i];
index++;
}
return sales;
}
} | Function where admin can withdraw all unused funds. | function withdrawUnusedFunds() external onlyAdmin {
uint256 balanceFTM = address(this).balance;
uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised;
safeTransferFTM(
msg.sender,
balanceFTM.sub(totalReservedForRaise.add(registrationFees))
);
}
| 12,826,389 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IFactorySafeHelper.sol";
import "./interfaces/IGnosisSafe.sol";
import "./interfaces/IGnosisSafeProxyFactory.sol";
import "./interfaces/IGnosisSafeModuleProxyFactory.sol";
import "./interfaces/IWyvernProxyRegistry.sol";
contract FactorySafeHelper is IFactorySafeHelper {
IGnosisSafeProxyFactory public immutable GNOSIS_SAFE_PROXY_FACTORY;
IGnosisSafeModuleProxyFactory
public immutable GNOSIS_SAFE_MODULE_PROXY_FACTORY;
address public immutable ORACLE;
address public immutable GNOSIS_SAFE_TEMPLATE_ADDRESS;
address public immutable GNOSIS_SAFE_FALLBACK_HANDLER;
address public immutable REALITY_MODULE_TEMPLATE_ADDRESS;
address public immutable WYVERN_PROXY_REGISTRY;
address public immutable SZNS_DAO;
uint256 public immutable REALITIO_TEMPLATE_ID;
uint256 public immutable DAO_MODULE_BOND;
uint32 public immutable DAO_MODULE_EXPIRATION;
uint32 public immutable DAO_MODULE_TIMEOUT;
constructor(
address proxyFactoryAddress,
address moduleProxyFactoryAddress,
address realitioAddress,
address safeTemplateAddress,
address safeFallbackHandler,
address realityModuleTemplateAddress,
address wyvernProxyRegistry,
address sznsDao,
uint256 realitioTemplateId,
uint256 bond,
uint32 expiration,
uint32 timeout
) {
GNOSIS_SAFE_PROXY_FACTORY = IGnosisSafeProxyFactory(
proxyFactoryAddress
);
GNOSIS_SAFE_MODULE_PROXY_FACTORY = IGnosisSafeModuleProxyFactory(
moduleProxyFactoryAddress
);
ORACLE = realitioAddress;
GNOSIS_SAFE_TEMPLATE_ADDRESS = safeTemplateAddress;
GNOSIS_SAFE_FALLBACK_HANDLER = safeFallbackHandler;
REALITY_MODULE_TEMPLATE_ADDRESS = realityModuleTemplateAddress;
WYVERN_PROXY_REGISTRY = wyvernProxyRegistry;
SZNS_DAO = sznsDao;
REALITIO_TEMPLATE_ID = realitioTemplateId;
DAO_MODULE_BOND = bond;
DAO_MODULE_EXPIRATION = expiration;
DAO_MODULE_TIMEOUT = timeout;
}
function createAndSetupSafe(bytes32 salt)
external
override
returns (address safeAddress, address realityModule)
{
salt = keccak256(abi.encode(salt, msg.sender, address(this)));
// Deploy safe
IGnosisSafe safe = GNOSIS_SAFE_PROXY_FACTORY.createProxyWithNonce(
GNOSIS_SAFE_TEMPLATE_ADDRESS,
"",
uint256(salt)
);
safeAddress = address(safe);
// Deploy reality module
realityModule = GNOSIS_SAFE_MODULE_PROXY_FACTORY.deployModule(
REALITY_MODULE_TEMPLATE_ADDRESS,
abi.encodeWithSignature(
"setUp(bytes)",
abi.encode(
safeAddress,
safeAddress,
safeAddress,
ORACLE,
DAO_MODULE_TIMEOUT,
0, // cooldown, hard-coded to 0
DAO_MODULE_EXPIRATION,
DAO_MODULE_BOND,
REALITIO_TEMPLATE_ID,
SZNS_DAO
)
),
0 // salt
);
// Initialize safe
address[] memory owners = new address[](1);
owners[0] = 0x000000000000000000000000000000000000dEaD;
safe.setup(
owners, // owners
1, // threshold
address(this), // to
abi.encodeCall( // data
this.initSafe,
(realityModule, WYVERN_PROXY_REGISTRY)
),
GNOSIS_SAFE_FALLBACK_HANDLER, // fallbackHandler
address(0), // paymentToken
0, // payment
payable(0) // paymentReceiver
);
}
function initSafe(
address realityModuleAddress,
address wyvernProxyRegistryAddress
) external {
IGnosisSafe(address(this)).enableModule(realityModuleAddress);
IWyvernProxyRegistry(wyvernProxyRegistryAddress).registerProxy();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFactorySafeHelper {
function createAndSetupSafe(bytes32 salt)
external
returns (address safeAddress, address);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
// Pared down version of @gnosis.pm/safe-contracts/contracts/GnosisSafe.sol
/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
interface IGnosisSafe {
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external;
/// @dev Allows to add a module to the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Enables the module `module` for the Safe.
/// @param module Module to be whitelisted.
function enableModule(address module) external;
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) external view returns (bool);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
// Pared down version of @gnosis.pm/safe-contracts/contracts/proxies/GnosisSafeProxyFactory.sol
import {IGnosisSafe} from "./IGnosisSafe.sol";
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <[email protected]>
interface IGnosisSafeProxyFactory {
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) external returns (IGnosisSafe proxy);
function proxyCreationCode() external pure returns (bytes memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGnosisSafeModuleProxyFactory {
function deployModule(
address masterCopy,
bytes memory initializer,
uint256 saltNonce
) external returns (address proxy);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWyvernProxyRegistry {
function registerProxy() external returns (address proxy);
} | Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction. Stefan George - <[email protected]> | interface IGnosisSafeProxyFactory {
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) external returns (IGnosisSafe proxy);
function proxyCreationCode() external pure returns (bytes memory);
}
pragma solidity >=0.7.0 <0.9.0;
import {IGnosisSafe} from "./IGnosisSafe.sol";
}
| 5,845,245 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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/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;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the 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.9;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
abstract contract ERC721Base is IERC165, IERC721 {
using Address for address;
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant ERC165ID = 0x01ffc9a7;
uint256 internal constant OPERATOR_FLAG = 0x8000000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant NOT_OPERATOR_FLAG = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
mapping(uint256 => uint256) internal _owners;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => bool)) internal _operatorsForAll;
mapping(uint256 => address) internal _operators;
function name() public pure virtual returns (string memory) {
revert("NOT_IMPLEMENTED");
}
/// @notice Approve an operator to transfer a specific token on the senders behalf.
/// @param operator The address receiving the approval.
/// @param id The id of the token.
function approve(address operator, uint256 id) external override {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(msg.sender == owner || _operatorsForAll[owner][msg.sender], "UNAUTHORIZED_APPROVAL");
_approveFor(owner, blockNumber, operator, id);
}
/// @notice Transfer a token between 2 addresses.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function transferFrom(
address from,
address to,
uint256 id
) external override {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(owner == from, "NOT_OWNER");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
if (msg.sender != from) {
require(
(operatorEnabled && _operators[id] == msg.sender) || _operatorsForAll[from][msg.sender],
"UNAUTHORIZED_TRANSFER"
);
}
_transferFrom(from, to, id);
}
/// @notice Transfer a token between 2 addresses letting the receiver know of the transfer.
/// @param from The send of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function safeTransferFrom(
address from,
address to,
uint256 id
) external override {
safeTransferFrom(from, to, id, "");
}
/// @notice Set the approval for an operator to manage all the tokens of the sender.
/// @param operator The address receiving the approval.
/// @param approved The determination of the approval.
function setApprovalForAll(address operator, bool approved) external override {
_setApprovalForAll(msg.sender, operator, approved);
}
/// @notice Get the number of tokens owned by an address.
/// @param owner The address to look for.
/// @return balance The number of tokens owned by the address.
function balanceOf(address owner) public view override returns (uint256 balance) {
require(owner != address(0), "ZERO_ADDRESS_OWNER");
balance = _balances[owner];
}
/// @notice Get the owner of a token.
/// @param id The id of the token.
/// @return owner The address of the token owner.
function ownerOf(uint256 id) external view override returns (address owner) {
owner = _ownerOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
}
/// @notice Get the owner of a token and the blockNumber of the last transfer, useful to voting mechanism.
/// @param id The id of the token.
/// @return owner The address of the token owner.
/// @return blockNumber The blocknumber at which the last transfer of that id happened.
function ownerAndLastTransferBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) {
return _ownerAndBlockNumberOf(id);
}
struct OwnerData {
address owner;
uint256 lastTransferBlockNumber;
}
/// @notice Get the list of owner of a token and the blockNumber of its last transfer, useful to voting mechanism.
/// @param ids The list of token ids to check.
/// @return ownersData The list of (owner, lastTransferBlockNumber) for each ids given as input.
function ownerAndLastTransferBlockNumberList(uint256[] calldata ids)
external
view
returns (OwnerData[] memory ownersData)
{
ownersData = new OwnerData[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 data = _owners[ids[i]];
ownersData[i].owner = address(uint160(data));
ownersData[i].lastTransferBlockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF;
}
}
/// @notice Get the approved operator for a specific token.
/// @param id The id of the token.
/// @return The address of the operator.
function getApproved(uint256 id) external view override returns (address) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
if (operatorEnabled) {
return _operators[id];
} else {
return address(0);
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isOperator) {
return _operatorsForAll[owner][operator];
}
/// @notice Transfer a token between 2 addresses letting the receiver knows of the transfer.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
/// @param data Additional data.
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public override {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(owner == from, "NOT_OWNER");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
if (msg.sender != from) {
require(
(operatorEnabled && _operators[id] == msg.sender) || _operatorsForAll[from][msg.sender],
"UNAUTHORIZED_TRANSFER"
);
}
_safeTransferFrom(from, to, id, data);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
return id == 0x01ffc9a7 || id == 0x80ac58cd || id == 0x5b5e139f;
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) internal {
_transferFrom(from, to, id);
if (to.isContract()) {
require(_checkOnERC721Received(msg.sender, from, to, id, data), "ERC721_TRANSFER_REJECTED");
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal virtual {}
function _transferFrom(
address from,
address to,
uint256 id
) internal {
_beforeTokenTransfer(from, to, id);
unchecked {
_balances[to]++;
if (from != address(0)) {
_balances[from]--;
}
}
_owners[id] = (block.number << 160) | uint256(uint160(to));
emit Transfer(from, to, id);
}
/// @dev See approve.
function _approveFor(
address owner,
uint256 blockNumber,
address operator,
uint256 id
) internal {
if (operator == address(0)) {
_owners[id] = (blockNumber << 160) | uint256(uint160(owner));
} else {
_owners[id] = OPERATOR_FLAG | (blockNumber << 160) | uint256(uint160(owner));
_operators[id] = operator;
}
emit Approval(owner, operator, id);
}
/// @dev See setApprovalForAll.
function _setApprovalForAll(
address sender,
address operator,
bool approved
) internal {
_operatorsForAll[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @dev Check if receiving contract accepts erc721 transfers.
/// @param operator The address of the operator.
/// @param from The from address, may be different from msg.sender.
/// @param to The adddress we want to transfer to.
/// @param id The id of the token we would like to transfer.
/// @param _data Any additional data to send with the transfer.
/// @return Whether the expected value of 0x150b7a02 is returned.
function _checkOnERC721Received(
address operator,
address from,
address to,
uint256 id,
bytes memory _data
) internal returns (bool) {
bytes4 retval = IERC721Receiver(to).onERC721Received(operator, from, id, _data);
return (retval == ERC721_RECEIVED);
}
/// @dev See ownerOf
function _ownerOf(uint256 id) internal view returns (address owner) {
return address(uint160(_owners[id]));
}
/// @dev Get the owner and operatorEnabled status of a token.
/// @param id The token to query.
/// @return owner The owner of the token.
/// @return operatorEnabled Whether or not operators are enabled for this token.
function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) {
uint256 data = _owners[id];
owner = address(uint160(data));
operatorEnabled = (data & OPERATOR_FLAG) == OPERATOR_FLAG;
}
// @dev Get the owner and operatorEnabled status of a token.
/// @param id The token to query.
/// @return owner The owner of the token.
/// @return blockNumber the blockNumber at which the owner became the owner (last transfer).
function _ownerAndBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) {
uint256 data = _owners[id];
owner = address(uint160(data));
blockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF;
}
// from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed.
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract.
/// @return results The results from each of the calls passed in via data.
function multicall(bytes[] calldata data) public payable returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./ERC721Base.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "./IERC4494.sol";
abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
}
// SPDX-License-Identifier: BSD-3-Clause
/// @title Vote checkpointing for an ERC-721 token
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
// LICENSE
// ERC721Checkpointable.sol uses and modifies part of Compound Lab's Comp.sol:
// https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol
//
// Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// Checkpointing logic from Comp.sol has been used with the following modifications:
// - `delegates` is renamed to `_delegates` and is set to private
// - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike
// Comp.sol, returns the delegator's own address if there is no delegate.
// This avoids the delegator needing to "delegate to self" with an additional transaction
// - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks.
pragma solidity 0.8.9;
import "./ERC721BaseWithERC4494Permit.sol";
abstract contract ERC721Checkpointable is ERC721BaseWithERC4494Permit {
bool internal _useCheckpoints = true; // can only be disabled and never re-enabled
/// @notice Defines decimals as per ERC-20 convention to make integrations with 3rd party governance platforms easier
uint8 public constant decimals = 0;
/// @notice A record of each accounts delegate
mapping(address => address) private _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 delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @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 votes a delegator can delegate, which is the current balance of the delegator.
* @dev Used when calling `_delegate()`
*/
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), "ERC721Checkpointable::votesToDelegate: amount exceeds 96 bits");
}
/**
* @notice Overrides the standard `Comp.sol` delegates mapping to return
* the delegator's own address if they haven't delegated.
* This avoids having to delegate to oneself.
*/
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
/**
* @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes.
* @dev hooks into ERC721Base's `ERC721._transfer`
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
if (_useCheckpoints) {
/// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation
_moveDelegates(delegates(from), delegates(to), 1);
}
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
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 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))
)
);
// TODO support smart contract wallet via IERC721, require change in function signature to know which signer to call first
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ERC721Checkpointable::delegateBySig: invalid signature");
require(nonce == _userNonces[signatory]++, "ERC721Checkpointable::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "ERC721Checkpointable::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) public view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @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 getVotes(address account) external view returns (uint96) {
return getCurrentVotes(account);
}
/**
* @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, "ERC721Checkpointable::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;
}
/**
* @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 getPastVotes(address account, uint256 blockNumber) external view returns (uint96) {
return this.getPriorVotes(account, blockNumber);
}
function _delegate(address delegator, address delegatee) internal {
/// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, 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, "ERC721Checkpointable::_moveDelegates: 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, "ERC721Checkpointable::_moveDelegates: amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
"ERC721Checkpointable::_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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IERC4494 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Allows to retrieve current nonce for token
/// @param tokenId token id
/// @return current token nonce
function nonces(uint256 tokenId) external view returns (uint256);
/// @notice function to be called by anyone to approve `spender` using a Permit signature
/// @dev Anyone can call this to approve `spender`, even a third-party
/// @param spender the actor to approve
/// @param tokenId the token id
/// @param deadline the deadline for the permit to be used
/// @param signature permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory signature
) external;
}
interface IERC4494Alternative {
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Allows to retrieve current nonce for token
/// @param tokenId token id
/// @return current token nonce
function tokenNonces(uint256 tokenId) external view returns (uint256);
/// @notice function to be called by anyone to approve `spender` using a Permit signature
/// @dev Anyone can call this to approve `spender`, even a third-party
/// @param spender the actor to approve
/// @param tokenId the token id
/// @param deadline the deadline for the permit to be used
/// @param signature permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory signature
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
abstract contract WithSupportForOpenSeaProxies {
address internal immutable _proxyRegistryAddress;
constructor(address proxyRegistryAddress) {
_proxyRegistryAddress = proxyRegistryAddress;
}
function _isOpenSeaProxy(address owner, address operator) internal view returns (bool) {
if (_proxyRegistryAddress == address(0)) {
return false;
}
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
return address(proxyRegistry.proxies(owner)) == operator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./BleepsRoles.sol";
import "../base/ERC721Checkpointable.sol";
import "../interfaces/ITokenURI.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../base/WithSupportForOpenSeaProxies.sol";
contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ReverseRegistrar {
function setName(string memory name) external returns (bytes32);
}
interface ENS {
function owner(bytes32 node) external view returns (address);
}
contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface ITokenURI {
function tokenURI(uint256 id) external view returns (string memory);
function contractURI(address receiver, uint96 per10Thousands) external view returns (string memory);
} | Check if the contract supports an interface. id The id of the interface. return Whether the interface is supported. | function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
| 6,180,797 |
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/lib/prb-math/src/ud60x18/Casting.sol | Casts a UD60x18 number into uint128. Requirements: - x must be less than or equal to `MAX_UINT128`. | function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
| 9,308,660 |
./full_match/1/0xE588ceDcf59C18Fad513c0326B5D41F0E514Cd03/sources/contracts/TheShadesEffect.sol | This will pay HashLips Lab Team 5% of the initial sale. By leaving the following lines as they are you will contribute to the development of tools like this and many others. ============================================================================= ============================================================================= This will transfer the remaining contract balance to the owner. Do not remove this otherwise you will not be able to withdraw the funds. ============================================================================= ============================================================================= | function withdraw() public onlyOwner nonReentrant {
require(hs);
require(me);
require(os);
}
| 8,479,274 |
./full_match/3/0xd1cC73f50464607AfE48F4eF97FA414Da191a461/sources/browser/exchange.sol | ---------setters------- | function registerUser() private notPaused returns(bool success) {
if (registration[msg.sender] == 0) {
pivot = pivot.add(1);
registration[msg.sender] = pivot;
}
return true;
}
| 8,104,415 |
pragma solidity ^0.5.14;
import "truffle/Assert.sol";
import "../contracts/AssertBytes.sol";
import "../contracts/BytesLib.sol";
contract TestBytesLib1 {
using BytesLib for bytes;
bytes storageCheckBytes = hex"aabbccddeeff";
bytes storageCheckBytesZeroLength = hex"";
bytes storageBytes4 = hex"f00dfeed";
bytes storageBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes63 = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes64 = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes65 = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
bytes storageBytes70 = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
event LogBytes(bytes loggedBytes);
/**
* Sanity Checks
*/
function testSanityCheck() public {
// Assert library sanity checks
//
// Please don't change the ordering of the var definitions
// the order is purposeful for testing zero-length arrays
bytes memory checkBytes = hex"aabbccddeeff";
bytes memory checkBytesZeroLength = hex"";
bytes memory checkBytesRight = hex"aabbccddeeff";
bytes memory checkBytesZeroLengthRight = hex"";
bytes memory checkBytesWrongLength = hex"aa0000";
bytes memory checkBytesWrongContent = hex"aabbccddee00";
// This next line is needed in order for Truffle to activate the Solidity unit testing feature
// otherwise it doesn't interpret any events fired as results of tests
Assert.equal(uint256(1), uint256(1), "This should not fail! :D");
AssertBytes.equal(checkBytes, checkBytesRight, "Sanity check should be checking equal bytes arrays out.");
AssertBytes.notEqual(checkBytes, checkBytesWrongLength, "Sanity check should be checking different length bytes arrays out.");
AssertBytes.notEqual(checkBytes, checkBytesWrongContent, "Sanity check should be checking different content bytes arrays out.");
AssertBytes.equalStorage(storageCheckBytes, checkBytesRight, "Sanity check should be checking equal bytes arrays out. (Storage)");
AssertBytes.notEqualStorage(storageCheckBytes, checkBytesWrongLength, "Sanity check should be checking different length bytes arrays out. (Storage)");
AssertBytes.notEqualStorage(storageCheckBytes, checkBytesWrongContent, "Sanity check should be checking different content bytes arrays out. (Storage)");
// Zero-length checks
AssertBytes.equal(checkBytesZeroLength, checkBytesZeroLengthRight, "Sanity check should be checking equal zero-length bytes arrays out.");
AssertBytes.notEqual(checkBytesZeroLength, checkBytes, "Sanity check should be checking different length bytes arrays out.");
AssertBytes.equalStorage(storageCheckBytesZeroLength, checkBytesZeroLengthRight, "Sanity check should be checking equal zero-length bytes arrays out. (Storage)");
AssertBytes.notEqualStorage(storageCheckBytesZeroLength, checkBytes, "Sanity check should be checking different length bytes arrays out. (Storage)");
}
/**
* Memory Integrity Checks
*/
function testMemoryIntegrityCheck4Bytes() public {
bytes memory preBytes4 = hex"f00dfeed";
bytes memory postBytes4 = hex"f00dfeed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes4);
// Now we should make sure that all the other previously initialized arrays stayed the same
testBytes = hex"f00dfeed";
AssertBytes.equal(preBytes4, testBytes, "After a postBytes4 concat the preBytes4 integrity check failed.");
AssertBytes.equal(postBytes4, testBytes, "After a postBytes4 concat the postBytes4 integrity check failed.");
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes31, testBytes, "After a postBytes4 concat the postBytes31 integrity check failed.");
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes32, testBytes, "After a postBytes4 concat the postBytes32 integrity check failed.");
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes33, testBytes, "After a postBytes4 concat the postBytes33 integrity check failed.");
}
function testMemoryIntegrityCheck31Bytes() public {
bytes memory preBytes4 = hex"f00dfeed";
bytes memory postBytes4 = hex"f00dfeed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes31);
// Now we should make sure that all the other previously initialized arrays stayed the same
testBytes = hex"f00dfeed";
AssertBytes.equal(preBytes4, testBytes, "After a postBytes31 concat the preBytes4 integrity check failed.");
AssertBytes.equal(postBytes4, testBytes, "After a postBytes31 concat the postBytes4 integrity check failed.");
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes31, testBytes, "After a postBytes31 concat the postBytes31 integrity check failed.");
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes32, testBytes, "After a postBytes31 concat the postBytes32 integrity check failed.");
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes33, testBytes, "After a postBytes31 concat the postBytes33 integrity check failed.");
}
function testMemoryIntegrityCheck32Bytes() public {
bytes memory preBytes4 = hex"f00dfeed";
bytes memory postBytes4 = hex"f00dfeed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes32);
// Now we should make sure that all the other previously initialized arrays stayed the same
testBytes = hex"f00dfeed";
AssertBytes.equal(preBytes4, testBytes, "After a postBytes32 concat the preBytes4 integrity check failed.");
AssertBytes.equal(postBytes4, testBytes, "After a postBytes32 concat the postBytes4 integrity check failed.");
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes31, testBytes, "After a postBytes32 concat the postBytes31 integrity check failed.");
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes32, testBytes, "After a postBytes32 concat the postBytes32 integrity check failed.");
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes33, testBytes, "After a postBytes32 concat the postBytes33 integrity check failed.");
}
function testMemoryIntegrityCheck33Bytes() public {
bytes memory preBytes4 = hex"f00dfeed";
bytes memory postBytes4 = hex"f00dfeed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes33);
// Now we should make sure that all the other previously initialized arrays stayed the same
testBytes = hex"f00dfeed";
AssertBytes.equal(preBytes4, testBytes, "After a postBytes33 concat the preBytes4 integrity check failed.");
AssertBytes.equal(postBytes4, testBytes, "After a postBytes33 concat the postBytes4 integrity check failed.");
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes31, testBytes, "After a postBytes33 concat the postBytes31 integrity check failed.");
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes32, testBytes, "After a postBytes33 concat the postBytes32 integrity check failed.");
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(postBytes33, testBytes, "After a postBytes33 concat the postBytes33 integrity check failed.");
}
/**
* Memory Concatenation Tests
*/
function testConcatMemory4Bytes() public {
// Initialize `bytes` variables in memory with different critical sizes
bytes memory preBytes4 = hex"f00dfeed";
bytes memory preBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes4 = hex"f00dfeed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes4);
testBytes = hex"f00dfeedf00dfeed";
AssertBytes.equal(resultBytes, testBytes, "preBytes4 + postBytes4 concatenation failed.");
resultBytes = preBytes31.concat(postBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equal(resultBytes, testBytes, "preBytes31 + postBytes4 concatenation failed.");
resultBytes = preBytes32.concat(postBytes4);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equal(resultBytes, testBytes, "preBytes32 + postBytes4 concatenation failed.");
resultBytes = preBytes33.concat(postBytes4);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equal(resultBytes, testBytes, "preBytes33 + postBytes4 concatenation failed.");
}
function testConcatMemory31Bytes() public {
// Initialize `bytes` variables in memory with different critical sizes
bytes memory preBytes4 = hex"f00dfeed";
bytes memory preBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes31);
testBytes = hex"f00dfeedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes4 + postBytes31 concatenation failed.");
resultBytes = preBytes31.concat(postBytes31);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes31 + postBytes31 concatenation failed.");
resultBytes = preBytes32.concat(postBytes31);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes32 + postBytes31 concatenation failed.");
resultBytes = preBytes33.concat(postBytes31);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes33 + postBytes31 concatenation failed.");
}
function testConcatMemory32Bytes() public {
// Initialize `bytes` variables in memory with different critical sizes
bytes memory preBytes4 = hex"f00dfeed";
bytes memory preBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes32);
testBytes = hex"f00dfeedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes4 + postBytes32 concatenation failed.");
resultBytes = preBytes31.concat(postBytes32);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes31 + postBytes32 concatenation failed.");
resultBytes = preBytes32.concat(postBytes32);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes32 + postBytes32 concatenation failed.");
resultBytes = preBytes33.concat(postBytes32);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes33 + postBytes32 concatenation failed.");
}
function testConcatMemory33Bytes() public {
// Initialize `bytes` variables in memory with different critical sizes
bytes memory preBytes4 = hex"f00dfeed";
bytes memory preBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory preBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
// And another set of the same to concatenate with
bytes memory postBytes4 = hex"f00dfeed";
bytes memory postBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
bytes memory postBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preBytes4.concat(postBytes33);
testBytes = hex"f00dfeedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes4 + postBytes33 concatenation failed.");
resultBytes = preBytes31.concat(postBytes33);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes31 + postBytes33 concatenation failed.");
resultBytes = preBytes32.concat(postBytes33);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes32 + postBytes33 concatenation failed.");
resultBytes = preBytes33.concat(postBytes33);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equal(resultBytes, testBytes, "preBytes33 + postBytes33 concatenation failed.");
}
/**
* Storage Concatenation Tests
*/
function testConcatStorage4Bytes() public {
// Initialize `bytes` variables in memory
bytes memory memBytes4 = hex"f00dfeed";
// this next assembly block is to guarantee that the block of memory next to the end of the bytes
// array is not zero'ed out
assembly {
let mc := mload(0x40)
mstore(mc, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
mstore(0x40, add(mc, 0x20))
}
bytes memory testBytes;
storageBytes4.concatStorage(memBytes4);
testBytes = hex"f00dfeedf00dfeed";
AssertBytes.equalStorage(storageBytes4, testBytes, "storageBytes4 + memBytes4 concatenation failed.");
storageBytes31.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes31, testBytes, "storageBytes31 + memBytes4 concatenation failed.");
storageBytes32.concatStorage(memBytes4);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes32, testBytes, "storageBytes32 + memBytes4 concatenation failed.");
storageBytes33.concatStorage(memBytes4);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes33, testBytes, "storageBytes33 + memBytes4 concatenation failed.");
storageBytes63.concatStorage(memBytes4);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes63, testBytes, "storageBytes63 + memBytes4 concatenation failed.");
storageBytes64.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes64, testBytes, "storageBytes64 + memBytes4 concatenation failed.");
storageBytes65.concatStorage(memBytes4);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes65, testBytes, "storageBytes65 + memBytes4 concatenation failed.");
storageBytes70.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes70, testBytes, "storageBytes70 + memBytes4 concatenation failed.");
resetStorage();
}
function testConcatStorage31Bytes() public {
// Initialize `bytes` variables in memory
bytes memory memBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
// this next assembly block is to guarantee that the block of memory next to the end of the bytes
// array is not zero'ed out
assembly {
let mc := mload(0x40)
mstore(mc, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
mstore(0x40, add(mc, 0x20))
}
bytes memory testBytes;
storageBytes4.concatStorage(memBytes31);
testBytes = hex"f00dfeedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes4, testBytes, "storageBytes4 + memBytes31 concatenation failed.");
storageBytes31.concatStorage(memBytes31);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes31, testBytes, "storageBytes31 + memBytes31 concatenation failed.");
storageBytes32.concatStorage(memBytes31);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes32, testBytes, "storageBytes32 + memBytes31 concatenation failed.");
storageBytes33.concatStorage(memBytes31);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes33, testBytes, "storageBytes33 + memBytes31 concatenation failed.");
storageBytes63.concatStorage(memBytes31);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes63, testBytes, "storageBytes63 + memBytes31 concatenation failed.");
storageBytes64.concatStorage(memBytes31);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes64, testBytes, "storageBytes64 + memBytes31 concatenation failed.");
storageBytes65.concatStorage(memBytes31);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes65, testBytes, "storageBytes65 + memBytes31 concatenation failed.");
storageBytes70.concatStorage(memBytes31);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes70, testBytes, "storageBytes70 + memBytes31 concatenation failed.");
resetStorage();
}
function testConcatStorage32Bytes() public {
// Initialize `bytes` variables in memory
bytes memory memBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
// this next assembly block is to guarantee that the block of memory next to the end of the bytes
// array is not zero'ed out
assembly {
let mc := mload(0x40)
mstore(mc, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
mstore(0x40, add(mc, 0x20))
}
bytes memory testBytes;
storageBytes4.concatStorage(memBytes32);
testBytes = hex"f00dfeedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes4, testBytes, "storageBytes4 + memBytes32 concatenation failed.");
storageBytes31.concatStorage(memBytes32);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes31, testBytes, "storageBytes31 + memBytes32 concatenation failed.");
storageBytes32.concatStorage(memBytes32);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes32, testBytes, "storageBytes32 + memBytes32 concatenation failed.");
storageBytes33.concatStorage(memBytes32);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes33, testBytes, "storageBytes33 + memBytes32 concatenation failed.");
storageBytes63.concatStorage(memBytes32);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes63, testBytes, "storageBytes63 + memBytes32 concatenation failed.");
storageBytes64.concatStorage(memBytes32);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes64, testBytes, "storageBytes64 + memBytes32 concatenation failed.");
storageBytes65.concatStorage(memBytes32);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes65, testBytes, "storageBytes65 + memBytes32 concatenation failed.");
storageBytes70.concatStorage(memBytes32);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d00000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes70, testBytes, "storageBytes70 + memBytes32 concatenation failed.");
resetStorage();
}
function testConcatStorage33Bytes() public {
// Initialize `bytes` variables in memory
bytes memory memBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
// this next assembly block is to guarantee that the block of memory next to the end of the bytes
// array is not zero'ed out
assembly {
let mc := mload(0x40)
mstore(mc, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
mstore(0x40, add(mc, 0x20))
}
bytes memory testBytes;
storageBytes4.concatStorage(memBytes33);
testBytes = hex"f00dfeedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes4, testBytes, "storageBytes4 + memBytes33 concatenation failed.");
storageBytes31.concatStorage(memBytes33);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes31, testBytes, "storageBytes31 + memBytes33 concatenation failed.");
storageBytes32.concatStorage(memBytes33);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes32, testBytes, "storageBytes32 + memBytes33 concatenation failed.");
storageBytes33.concatStorage(memBytes33);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes33, testBytes, "storageBytes33 + memBytes33 concatenation failed.");
storageBytes63.concatStorage(memBytes33);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes63, testBytes, "storageBytes63 + memBytes33 concatenation failed.");
storageBytes64.concatStorage(memBytes33);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes64, testBytes, "storageBytes64 + memBytes33 concatenation failed.");
storageBytes65.concatStorage(memBytes33);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes65, testBytes, "storageBytes65 + memBytes33 concatenation failed.");
storageBytes70.concatStorage(memBytes33);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00d0000000000000000000000000000000000000000000000000000000000feed";
AssertBytes.equalStorage(storageBytes70, testBytes, "storageBytes70 + memBytes33 concatenation failed.");
resetStorage();
}
/**
* Edge Cases
*/
function testConcatMemoryZeroLength() public {
// Initialize `bytes` variables in memory with different critical sizes
bytes memory preZeroLength = hex"";
bytes memory postZeroLength = hex"";
bytes memory testBytes;
bytes memory resultBytes;
resultBytes = preZeroLength.concat(postZeroLength);
testBytes = hex"";
AssertBytes.equal(resultBytes, testBytes, "Zero Length concatenation failed.");
}
/**
* Helper Functions
*/
function resetStorage() internal {
storageBytes4 = hex"f00dfeed";
storageBytes31 = hex"f00d000000000000000000000000000000000000000000000000000000feed";
storageBytes32 = hex"f00d00000000000000000000000000000000000000000000000000000000feed";
storageBytes33 = hex"f00d0000000000000000000000000000000000000000000000000000000000feed";
storageBytes63 = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
storageBytes64 = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
storageBytes65 = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
storageBytes70 = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feed";
}
}
| Initialize `bytes` variables in memory this next assembly block is to guarantee that the block of memory next to the end of the bytes array is not zero'ed out | function testConcatStorage4Bytes() public {
bytes memory memBytes4 = hex"f00dfeed";
assembly {
let mc := mload(0x40)
mstore(mc, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
mstore(0x40, add(mc, 0x20))
}
bytes memory testBytes;
storageBytes4.concatStorage(memBytes4);
testBytes = hex"f00dfeedf00dfeed";
AssertBytes.equalStorage(storageBytes4, testBytes, "storageBytes4 + memBytes4 concatenation failed.");
storageBytes31.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes31, testBytes, "storageBytes31 + memBytes4 concatenation failed.");
storageBytes32.concatStorage(memBytes4);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes32, testBytes, "storageBytes32 + memBytes4 concatenation failed.");
storageBytes33.concatStorage(memBytes4);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes33, testBytes, "storageBytes33 + memBytes4 concatenation failed.");
storageBytes63.concatStorage(memBytes4);
testBytes = hex"f00d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes63, testBytes, "storageBytes63 + memBytes4 concatenation failed.");
storageBytes64.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes64, testBytes, "storageBytes64 + memBytes4 concatenation failed.");
storageBytes65.concatStorage(memBytes4);
testBytes = hex"f00d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes65, testBytes, "storageBytes65 + memBytes4 concatenation failed.");
storageBytes70.concatStorage(memBytes4);
testBytes = hex"f00d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000feedf00dfeed";
AssertBytes.equalStorage(storageBytes70, testBytes, "storageBytes70 + memBytes4 concatenation failed.");
resetStorage();
}
| 5,410,113 |
pragma solidity ^0.5.1;
contract ERC20Interface {
// 代币名称
string public name;
// 代币符号或者说简写
string public symbol;
// 代币小数点位数,代币的最小单位
uint8 public decimals;
// 代币的发行总量
uint public totalSupply;
// 实现代币交易,用于给某个地址转移代币
function transfer(address to, uint tokens) public returns (bool success);
// 实现代币用户之间的交易,从一个地址转移代币到另一个地址
function transferFrom(address from, address to, uint tokens) public returns (bool success);
// 允许spender多次从你的账户取款,并且最多可取tokens个,主要用于某些场景下授权委托其他用户从你的账户上花费代币
function approve(address spender, uint tokens) public returns (bool success);
// 查询spender允许从tokenOwner上花费的代币数量
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
// 代币交易时触发的事件,即调用transfer方法时触发
event Transfer(address indexed from, address indexed to, uint tokens);
// 允许其他用户从你的账户上花费代币时触发的事件,即调用approve方法时触发
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// 实现ERC-20标准接口
contract STAR is ERC20Interface {
// 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法)
mapping (address => uint256) public balanceOf;
// 存储每个地址可操作的地址及其可操作的金额
mapping (address => mapping (address => uint256)) internal allowed;
// 初始化属性
constructor() public {
name = "SUPER STAR";
symbol = "STAR";
decimals = 6;
totalSupply = 190000000 * 10**uint(decimals);
// 初始化该代币的账户会拥有所有的代币
balanceOf[msg.sender] = totalSupply;
}
function transfer(address to, uint tokens) public returns (bool success) {
// 检验接收者地址是否合法
require(to != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[msg.sender] >= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[msg.sender] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(msg.sender, to, tokens);
success = true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
// 检验地址是否合法
require(to != address(0) && from != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[from] >= tokens);
// 检验操作的金额是否是被允许的
require(allowed[from][msg.sender] <= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[from] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(from, to, tokens);
success = true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
// 触发相应的事件
emit Approval(msg.sender, spender, tokens);
success = true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
} | 检验地址是否合法 检验发送者账户余额是否足够 检验操作的金额是否是被允许的 检验是否会发生溢出 扣除发送者账户余额 增加接收者账户余额 触发相应的事件 | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(to != address(0) && from != address(0));
require(balanceOf[from] >= tokens);
require(allowed[from][msg.sender] <= tokens);
require(balanceOf[to] + tokens >= balanceOf[to]);
balanceOf[from] -= tokens;
balanceOf[to] += tokens;
emit Transfer(from, to, tokens);
success = true;
}
| 2,456,716 |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @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 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 PoSTokenStandard
* @dev the interface of PoSTokenStandard
*/
contract PoSTokenStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
//Scarcecoin -
function mint() returns (bool);
function coinAge(address who) constant returns (uint256);
function annualInterest() constant returns (uint256);
event Mint(address indexed _address, uint _reward);
}
//Scarcecoin - Changed name of contract
contract ScarceCoinToken is ERC20,PoSTokenStandard,Ownable {
using SafeMath for uint256;
//Scarcecoin - Changed name of contract
string public name = "ScarceCoinToken";
string public symbol = "SCO";
uint public decimals = 18;
uint public chainStartTime; //chain start time
uint public chainStartBlockNumber; //chain start block number
uint public stakeStartTime; //stake start time
uint public stakeMinAge = 3 days; // minimum age for coin age: 3D
uint public stakeMaxAge = 90 days; // stake age of full weight: 90D
uint public maxMintProofOfStake = 10**17; // default 10% annual interest
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
struct transferInStruct{
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => transferInStruct[]) transferIns;
//Scarcecoin - Removed burn system
//event Burn(address indexed burner, uint256 value);
/**
* @dev Fix for the ERC20 short address attack.
*/
uint etherCostOfEachToken = 10000000000000;
function() payable{
address collector = 0xC59C1f43da016674d599f8CaDC29d2Fe937bA061;
// etherCostOfEachToken = 10000000000000;
uint256 _value = msg.value / etherCostOfEachToken * 1 ether;
balances[msg.sender] = balances[msg.sender].add(_value);
totalSupply = totalSupply.sub(_value);
collector.transfer(msg.value);
}
function setEtherCostOfEachToken(uint etherCostOfEachToken) onlyOwner {
etherCostOfEachToken = etherCostOfEachToken;
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function ScarcecoinStart() onlyOwner {
address recipient;
uint value;
uint64 _now = uint64(now);
//kill start if this has already been ran
require((maxTotalSupply <= 0));
maxTotalSupply = 1.4*(10**28); // 14 Bil.
//Scarcecoin - Modified initial supply to 14Bil
totalInitialSupply = 1*(10**27); // 1Bil
chainStartTime = now;
chainStartBlockNumber = block.number;
//Reserved coin for bounty, promotion and team - 400Mil
recipient = 0xC59C1f43da016674d599f8CaDC29d2Fe937bA061;
value = 4 * (10**26);
//run
balances[recipient] = value;
transferIns[recipient].push(transferInStruct(uint128(value),_now));
totalSupply = totalInitialSupply;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
//Scarcecoin - Modified to mint
if(msg.sender == _to) return mint();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//Scarcecoin - Modified the correct technical term "mint" to a well know term "mint" for marketing purposes.
function mint() canPoSMint returns (bool) {
if(balances[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getProofOfStakeReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
//Scarcecoin - Change event to mint
Mint(msg.sender, reward);
return true;
}
function getBlockNumber() returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge(address who) constant returns (uint myCoinAge) {
myCoinAge = getCoinAge(who,now);
}
function annualInterest() constant returns(uint interest) {
uint _now = now;
interest = maxMintProofOfStake;
//Scarcecoin - Modified initial interest rate to 100%
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1) {
interest = (435 * maxMintProofOfStake).div(100);
}
}
function getProofOfStakeReward(address _address) internal returns (uint) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint _now = now;
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
uint interest = maxMintProofOfStake;
// Due to the high interest rate for the first two years, compounding should be taken into account.
// Effective annual interest rate = (1 + (nominal rate / number of compounding periods)) ^ (number of compounding periods) - 1
//Scarcecoin - Modified initial interest rate to 100%
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
// 1st year effective annual interest rate is 100% when we select the stakeMaxAge (90 days) as the compounding period.
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1) {
// 2nd year effective annual interest rate is 50% when we select the stakeMaxAge (90 days) as the compounding period.
interest = (435 * maxMintProofOfStake).div(100);
}
return (_coinAge * interest).div(365 * (10**decimals));
}
function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
function ownerSetStakeStartTime(uint timestamp) onlyOwner {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
} | Scarcecoin - Modified to mint | function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
if(msg.sender == _to) return mint();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
| 7,870,798 |
./full_match/5/0xDb80166478D50EDEFc4dD72c304d44D270c6b494/sources/contracts/core/libs/attestations-registry/InitializableLogic.sol | Internal function that returns the initialized version. Returns `_initializing`/ | function _isInitializing() internal view returns (bool) {
return _initializing;
}
| 1,931,193 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @author Dylon Wong Chung Yee
/// @title A ShelterNOW ERC-20 token contract.
contract ShelterNOW is IERC20, Context, Ownable {
// Mapping from owner to spender to allowance.
mapping(address => mapping(address => uint256)) private _allowances;
// Mapping from owner to respective balances
mapping(address => uint256) private _balances;
// Total token supply, set to 1 billion tokens with 9 decimals.
uint256 private _totalSupply = 1 * 1e12 * 1e9;
// Name of the ERC-20 token.
string private _name = "ShelterNOW";
// Symbol of the ERC-20 token.
string private _symbol = "SNOW";
// Decimals for display purpose.
uint8 private _decimals = 9;
/**
* @dev Initializes the contract by setting an initial supply of token.
*/
constructor() {
address _owner = _msgSender();
_mint(_owner, _totalSupply);
}
/**
* @dev Get the name of this token.
*
* @return The name.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Get the symbol of this token.
*
* @return The symbol.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Get the decimals of this token collection.
*
* @return The decimals.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Get the total supply of this token collection.
*
* @return The total supply.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Get the balance of an address.
*
* @param account: The address of an account to query.
*
* @return The balance.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev Transfer token to another address.
*
* @param to: The receipient of the transaction.
* @param amount: The amount of token to be transferred.
*
* @return Successful or not.
*/
function transfer(address to, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), to, amount);
return true;
}
/**
* @dev Get the allowance approved to a spender of an owner.
*
* @param owner_: The owner's address to query.
* @param spender: The spender's address approved by the owner.
*
* @return The token spending allowance.
*/
function allowance(address owner_, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner_][spender];
}
/**
* @dev Approve a spender to spend an amount of allowance.
*
* @param spender: The spender's address to be approved.
* @param amount: The amount of allowance approved by the owner.
*
* @return Successful or not.
*/
function approve(address spender, uint256 amount)
public
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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
_spendAllowance(from, _msgSender(), amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
address owner_ = _msgSender();
_approve(owner_, spender, allowance(owner_, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
address owner_ = _msgSender();
uint256 currentAllowance = allowance(owner_, spender);
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(owner_, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner_` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner_` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner_,
address spender,
uint256 amount
) internal {
require(owner_ != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner_][spender] = amount;
emit Approval(owner_, spender, amount);
}
/**
* @dev Updates `owner_` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner_,
address spender,
uint256 amount
) internal {
uint256 currentAllowance = allowance(owner_, spender);
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"ERC20: insufficient allowance"
);
unchecked {
_approve(owner_, spender, currentAllowance - amount);
}
}
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(
fromBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
}
| Updates `owner_` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./ | function _spendAllowance(
address owner_,
address spender,
uint256 amount
) internal {
uint256 currentAllowance = allowance(owner_, spender);
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"ERC20: insufficient allowance"
);
unchecked {
_approve(owner_, spender, currentAllowance - amount);
}
}
}
| 975,482 |
pragma solidity ^0.6.12;
abstract contract Context {
function _MSGSENDER292() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA848() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY965() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF795(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER536(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE225(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE133(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM756(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER325(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL100(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD676(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB200(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB200(a, b, "SafeMath: subtraction overflow");
}
function SUB200(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 MUL199(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 DIV336(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV336(a, b, "SafeMath: division by zero");
}
function DIV336(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 MOD258(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD258(a, b, "SafeMath: modulo by zero");
}
function MOD258(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT4(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE907(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 FUNCTIONCALL885(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL885(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL885(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE995(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE204(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE204(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE204(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 _FUNCTIONCALLWITHVALUE995(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE995(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT4(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 SAFETRANSFER58(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN724(token, abi.encodeWithSelector(token.TRANSFER536.selector, to, value));
}
function SAFETRANSFERFROM571(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN724(token, abi.encodeWithSelector(token.TRANSFERFROM756.selector, from, to, value));
}
function SAFEAPPROVE498(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.ALLOWANCE225(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN724(token, abi.encodeWithSelector(token.APPROVE133.selector, spender, value));
}
function SAFEINCREASEALLOWANCE127(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE225(address(this), spender).ADD676(value);
_CALLOPTIONALRETURN724(token, abi.encodeWithSelector(token.APPROVE133.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE22(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE225(address(this), spender).SUB200(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN724(token, abi.encodeWithSelector(token.APPROVE133.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN724(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).FUNCTIONCALL885(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");
}
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED970(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER292();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED970(address(0), msgSender);
}
function OWNER239() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER200() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER292(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP850() public virtual ONLYOWNER200 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED970(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP80(address newOwner) public virtual ONLYOWNER200 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED970(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME337() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL333() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS747() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY965() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF795(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER536(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER104(_MSGSENDER292(), recipient, amount);
return true;
}
function ALLOWANCE225(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE133(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE753(_MSGSENDER292(), spender, amount);
return true;
}
function TRANSFERFROM756(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER104(sender, recipient, amount);
_APPROVE753(sender, _MSGSENDER292(), _allowances[sender][_MSGSENDER292()].SUB200(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE697(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE753(_MSGSENDER292(), spender, _allowances[_MSGSENDER292()][spender].ADD676(addedValue));
return true;
}
function DECREASEALLOWANCE977(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE753(_MSGSENDER292(), spender, _allowances[_MSGSENDER292()][spender].SUB200(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER104(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER536(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB200(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD676(amount);
emit TRANSFER325(sender, recipient, amount);
}
function _MINT956(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER536(address(0), account, amount);
_totalSupply = _totalSupply.ADD676(amount);
_balances[account] = _balances[account].ADD676(amount);
emit TRANSFER325(address(0), account, amount);
}
function _BURN958(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER536(account, address(0), amount);
_balances[account] = _balances[account].SUB200(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB200(amount);
emit TRANSFER325(account, address(0), amount);
}
function _APPROVE753(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
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 APPROVAL100(owner, spender, amount);
}
function _SETUPDECIMALS722(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER536(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// HuoguoToken with Governance.
contract HuoguoToken is ERC20("HUOGUO.finance", "HUOGUO"), Ownable {
function MINT320(address _to, uint256 _amount) public ONLYOWNER200 { //inject NONSTANDARD NAMING
_MINT956(_to, _amount);
}
}
contract HuoguoChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HUOGUOs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHuoguoPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accHuoguoPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HUOGUOs to distribute per block.
uint256 lastRewardBlock; // Last block number that HUOGUOs distribution occurs.
uint256 accHuoguoPerShare; // Accumulated HUOGUOs per share, times 1e12. See below.
}
// The HUOGUO TOKEN!
HuoguoToken public huoguo;
// Dev address.
address public devaddr;
// Block number when bonus HUOGUO period ends.
uint256 public bonusEndBlock;
// HUOGUO tokens created per block.
uint256 public huoguoPerBlock;
// Bonus muliplier for early huoguo makers.
uint256 public constant bonus_multiplier198 = 1; // no bonus //inject NONSTANDARD NAMING
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when HUOGUO mining starts.
uint256 public startBlock;
event DEPOSIT766(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW854(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW584(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
constructor(
HuoguoToken _huoguo,
address _devaddr,
uint256 _huoguoPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
huoguo = _huoguo;
devaddr = _devaddr;
huoguoPerBlock = _huoguoPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function POOLLENGTH693() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function ADD676(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public ONLYOWNER200 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS170();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.ADD676(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accHuoguoPerShare: 0
}));
}
// Update the given pool's HUOGUO allocation point. Can only be called by the owner.
function SET574(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public ONLYOWNER200 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS170();
}
totalAllocPoint = totalAllocPoint.SUB200(poolInfo[_pid].allocPoint).ADD676(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function GETMULTIPLIER700(uint256 _from, uint256 _to) public view returns (uint256) { //inject NONSTANDARD NAMING
if (_to <= bonusEndBlock) {
return _to.SUB200(_from).MUL199(bonus_multiplier198);
} else if (_from >= bonusEndBlock) {
return _to.SUB200(_from);
} else {
return bonusEndBlock.SUB200(_from).MUL199(bonus_multiplier198).ADD676(
_to.SUB200(bonusEndBlock)
);
}
}
// View function to see pending HUOGUOs on frontend.
function PENDINGHUOGUO703(uint256 _pid, address _user) external view returns (uint256) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHuoguoPerShare = pool.accHuoguoPerShare;
uint256 lpSupply = pool.lpToken.BALANCEOF795(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = GETMULTIPLIER700(pool.lastRewardBlock, block.number);
uint256 huoguoReward = multiplier.MUL199(huoguoPerBlock).MUL199(pool.allocPoint).DIV336(totalAllocPoint);
accHuoguoPerShare = accHuoguoPerShare.ADD676(huoguoReward.MUL199(1e12).DIV336(lpSupply));
}
return user.amount.MUL199(accHuoguoPerShare).DIV336(1e12).SUB200(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS170() public { //inject NONSTANDARD NAMING
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
UPDATEPOOL251(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function MINT320(uint256 amount) public ONLYOWNER200{ //inject NONSTANDARD NAMING
huoguo.MINT320(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL251(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.BALANCEOF795(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = GETMULTIPLIER700(pool.lastRewardBlock, block.number);
uint256 huoguoReward = multiplier.MUL199(huoguoPerBlock).MUL199(pool.allocPoint).DIV336(totalAllocPoint);
huoguo.MINT320(devaddr, huoguoReward.DIV336(20)); // 5%
huoguo.MINT320(address(this), huoguoReward);
pool.accHuoguoPerShare = pool.accHuoguoPerShare.ADD676(huoguoReward.MUL199(1e12).DIV336(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for HUOGUO allocation.
function DEPOSIT520(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UPDATEPOOL251(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.MUL199(pool.accHuoguoPerShare).DIV336(1e12).SUB200(user.rewardDebt);
SAFEHUOGUOTRANSFER588(msg.sender, pending);
}
pool.lpToken.SAFETRANSFERFROM571(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD676(_amount);
user.rewardDebt = user.amount.MUL199(pool.accHuoguoPerShare).DIV336(1e12);
emit DEPOSIT766(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function WITHDRAW519(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
UPDATEPOOL251(_pid);
uint256 pending = user.amount.MUL199(pool.accHuoguoPerShare).DIV336(1e12).SUB200(user.rewardDebt);
SAFEHUOGUOTRANSFER588(msg.sender, pending);
user.amount = user.amount.SUB200(_amount);
user.rewardDebt = user.amount.MUL199(pool.accHuoguoPerShare).DIV336(1e12);
pool.lpToken.SAFETRANSFER58(address(msg.sender), _amount);
emit WITHDRAW854(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function EMERGENCYWITHDRAW628(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.SAFETRANSFER58(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW584(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe huoguo transfer function, just in case if rounding error causes pool to not have enough HUOGUOs.
function SAFEHUOGUOTRANSFER588(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 huoguoBal = huoguo.BALANCEOF795(address(this));
if (_amount > huoguoBal) {
huoguo.TRANSFER536(_to, huoguoBal);
} else {
huoguo.TRANSFER536(_to, _amount);
}
}
// Update dev address by the previous dev.
function DEV515(address _devaddr) public { //inject NONSTANDARD NAMING
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | inject NONSTANDARD NAMING | function DIV336(uint256 a, uint256 b) internal pure returns (uint256) { | 12,993,966 |
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-core/pool/WormholeAdaptor.sol | Delivery fee attached to the txn is done off-chain via `estimateDeliveryFee` to reduce gas cost Unused `deliveryGasLimit` is sent to the `refundAddress` (`receiver`). (emitterChainID, emitterAddress, sequence) is used to retrive the generated VAA from the Guardian Network and for tracking | function _bridgeCreditAndSwapForTokens(
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address receiver,
uint256 receiverValue,
uint256 deliveryGasLimit
) internal override returns (uint256 sequence) {
require(toChain <= type(uint16).max, 'invalid chain ID');
);
}
| 2,762,596 |
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
contract Ownable {
address payable public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
interface CTokenInterface {
function redeemUnderlying(uint redeemAmount) external returns (uint);
}
interface CETHInterface {
function mint() external payable; // For ETH
}
interface ERC20Interface {
function allowance(address, address) external view returns (uint);
function balanceOf(address) external view returns (uint);
function approve(address, uint) external;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
}
contract AutoETHSavingsAccount is Ownable, ReentrancyGuard{
using SafeMath for uint;
// state variables
address payable private savingsAccount;
uint public balance = address(this).balance;
bool private stopped = false;
//circuit breaker modifiers
modifier stopInEmergency {if (!stopped) _;}
modifier onlyInEmergency {if (stopped) _;}
constructor () public {
}
function toggleContractActive() onlyOwner public {
stopped = !stopped;
}
// this function lets you add and replace the old SavingsAccount in which the marginal savings will be deposited
function addSavingsAccounts (address payable _address) onlyOwner public {
savingsAccount = _address;
}
// this function lets you deposit ETH into this wallet
function depositETH() payable public returns (uint) {
balance += msg.value;
}
// fallback function let you / anyone send ETH to this wallet without the need to call any function
function() external payable {
balance += msg.value;
}
// Through this function you will be making a normal payment to any external address or a wallet address as in the normal situation
function payETH(address payable _to, uint _amount, uint _pettyAmount) stopInEmergency onlyOwner nonReentrant external returns (uint) {
uint grossPayableAmount = SafeMath.add(_amount, _pettyAmount);
require(balance > SafeMath.add(grossPayableAmount, 20000000000000000), "the balance held by the Contract is less than the amount required to be paid");
balance = balance - _amount - _pettyAmount;
savePettyCash(_pettyAmount);
_to.transfer(_amount);
}
// Depositing the savings amount into the Savings Account
function savePettyCash(uint _pettyAmount) internal {
savingsAccount.transfer(_pettyAmount);
}
function withdraw() onlyOwner onlyInEmergency public{
owner.transfer(address(this).balance);
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
function sub(uint x, uint y) internal pure returns (uint z) {
z = x - y <= x ? x - y : 0;
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
}
contract Helpers is DSMath {
/**
* @dev get ethereum address for trade
*/
function getAddressETH() public pure returns (address eth) {
eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
/**
* @dev get Compound Comptroller Address
*/
function getCETHAddress() public pure returns (address cEth) {
cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
}
/**
* @dev setting allowance to compound for the "user proxy" if required
*/
function setApproval(address erc20, uint srcAmt, address to) internal {
ERC20Interface erc20Contract = ERC20Interface(erc20);
uint tokenAllowance = erc20Contract.allowance(address(this), to);
if (srcAmt > tokenAllowance) {
erc20Contract.approve(to, 2**255);
}
}
}
contract CompoundResolver is Helpers {
event LogMint(address erc20, address cErc20, uint tokenAmt, address owner);
event LogRedeem(address erc20, address cErc20, uint tokenAmt, address owner);
/**
* @dev Deposit ETH/ERC20 and mint Compound Tokens
*/
function mintCEth(uint tokenAmt) internal {
CETHInterface cToken = CETHInterface(getCETHAddress());
cToken.mint.value(tokenAmt)();
emit LogMint(getAddressETH(),getCETHAddress(),tokenAmt, msg.sender);
}
/**
* @dev Redeem ETH/ERC20 and mint Compound Tokens
* @param tokenAmt Amount of token To Redeem
*/
function redeemEth(uint tokenAmt) internal {
CTokenInterface cToken = CTokenInterface(getCETHAddress());
setApproval(getCETHAddress(), 10**30, getCETHAddress());
require(cToken.redeemUnderlying(tokenAmt) == 0, "something went wrong");
emit LogRedeem(getAddressETH(),getCETHAddress(),tokenAmt, address(this));
}
}
| get Compound Comptroller Address/ | function getCETHAddress() public pure returns (address cEth) {
cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
}
| 5,428,378 |
/**
* @title: Cream DAI wrapper
* @summary: Used for interacting with Cream Finance. Has
* a common interface with all other protocol wrappers.
* This contract holds assets only during a tx, after tx it should be empty
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/ILendingProtocol.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/WhitePaperInterestRateModel.sol";
// This strategy is a modified version of the strategy made by Sunny with few improvements.
// This contract should be deployed with a minimal proxy factory
contract IdleCompoundLike is ILendingProtocol {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// protocol token (cTokenLike) address
address public token;
// underlying token (token eg DAI) address
address public underlying;
address public idleToken;
uint256 public blocksPerYear;
address public owner;
/**
* @param _token : cTokenLike address
* @param _idleToken : idleToken address
* @param _owner : contract owner (for eventually setting blocksPerYear)
*/
function initialize(address _token, address _idleToken, address _owner) public {
require(token == address(0), 'cTokenLike: already initialized');
require(_token != address(0), 'cTokenLike: addr is 0');
token = _token;
owner = _owner;
underlying = CERC20(_token).underlying();
idleToken = _idleToken;
blocksPerYear = 2371428;
IERC20(underlying).safeApprove(_token, uint256(-1));
}
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken");
_;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not IdleToken");
_;
}
/**
* sets blocksPerYear address
*
* @param _blocksPerYear : avg blocks per year
*/
function setBlocksPerYear(uint256 _blocksPerYear)
external onlyOwner {
require((blocksPerYear = _blocksPerYear) != 0, "_blocksPerYear is 0");
}
/**
* Calculate next supply rate for Compound, given an `_amount` supplied
*
* @param _amount : new underlying amount supplied (eg DAI)
* @return : yearly net rate
*/
function nextSupplyRate(uint256 _amount)
external view
returns (uint256) {
CERC20 cToken = CERC20(token);
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(CERC20(token).interestRateModel());
uint256 ratePerBlock = white.getSupplyRate(
cToken.getCash().add(_amount),
cToken.totalBorrows(),
cToken.totalReserves(),
cToken.reserveFactorMantissa()
);
return ratePerBlock.mul(blocksPerYear).mul(100);
}
/**
* @return current price of cTokenLike token
*/
function getPriceInToken()
external view
returns (uint256) {
return CERC20(token).exchangeRateStored();
}
/**
* @return current apr
*/
function getAPR()
external view
returns (uint256) {
// return nextSupplyRate(0);
// more efficient
return CERC20(token).supplyRatePerBlock().mul(blocksPerYear).mul(100);
}
/**
* Gets all underlying tokens in this contract and mints cTokenLike Tokens
* tokens are then transferred to msg.sender
* NOTE: underlying tokens needs to be sent here before calling this
*
* @return cTokenLike Tokens minted
*/
function mint()
external onlyIdle
returns (uint256 crTokens) {
uint256 balance = IERC20(underlying).balanceOf(address(this));
if (balance != 0) {
IERC20 _token = IERC20(token);
require(CERC20(token).mint(balance) == 0, "Error minting crTokens");
crTokens = _token.balanceOf(address(this));
_token.safeTransfer(msg.sender, crTokens);
}
}
/**
* Gets all cTokenLike in this contract and redeems underlying tokens.
* underlying tokens are then transferred to `_account`
* NOTE: cTokenLike needs to be sent here before calling this
*
* @return underlying tokens redeemd
*/
function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
require(CERC20(token).redeem(IERC20(token).balanceOf(address(this))) == 0, "Error redeeming crTokens");
IERC20 _underlying = IERC20(underlying);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
/**
* Get the underlying balance on the lending protocol
*
* @return underlying tokens available
*/
function availableLiquidity() external view returns (uint256) {
return CERC20(token).getCash();
}
}
| Get the underlying balance on the lending protocol return underlying tokens available/ | function availableLiquidity() external view returns (uint256) {
return CERC20(token).getCash();
}
| 6,347,466 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
interface Erc20 {
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
interface CEth {
function mint() external payable;
function exchangeRateCurrent() external returns (uint256);
function supplyRatePerBlock() external returns (uint256);
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function transfer(address, uint256) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function balanceOf(address owner) external view returns (uint256);
}
contract ScheDapp {
uint256 public fee = 0.001 ether;
event MyLog(string, uint256);
function supplyEthToCompound(address payable _cEtherContract)
public
payable
returns (bool)
{
require(msg.value >= fee, "Fee it's not enough!");
CEth cToken = CEth(_cEtherContract);
uint256 exchangeRateMantissa = cToken.exchangeRateCurrent();
emit MyLog("Exchange Rate (scaled up by 1e18): ", exchangeRateMantissa);
uint256 supplyRateMantissa = cToken.supplyRatePerBlock();
emit MyLog("Supply Rate: (scaled up by 1e18)", supplyRateMantissa);
cToken.mint{value: msg.value, gas: 250000}();
cToken.transferFrom(
address(this),
msg.sender,
cToken.balanceOf(address(this))
);
return true;
}
function redeemCEth(
uint256 amount,
bool redeemType,
address _cEtherContract
) public returns (bool) {
// Create a reference to the corresponding cToken contract
CEth cToken = CEth(_cEtherContract);
// `amount` is scaled up by 1e18 to avoid decimals
uint256 redeemResult;
if (redeemType == true) {
// Retrieve your asset based on a cToken amount
redeemResult = cToken.redeem(amount);
} else {
// Retrieve your asset based on an amount of the asset
redeemResult = cToken.redeemUnderlying(amount);
}
// Error codes are listed here:
// https://compound.finance/docs/ctokens#ctoken-error-codes
emit MyLog("If this is not 0, there was an error", redeemResult);
return true;
}
// This is needed to receive ETH when calling `redeemCEth`
receive() external payable {}
}
| Create a reference to the corresponding cToken contract `amount` is scaled up by 1e18 to avoid decimals Retrieve your asset based on a cToken amount Retrieve your asset based on an amount of the asset | function redeemCEth(
uint256 amount,
bool redeemType,
address _cEtherContract
) public returns (bool) {
CEth cToken = CEth(_cEtherContract);
uint256 redeemResult;
if (redeemType == true) {
redeemResult = cToken.redeem(amount);
redeemResult = cToken.redeemUnderlying(amount);
}
return true;
}
| 6,348,101 |
./full_match/80001/0xaAF8061494609136A34b02A74f0f55e3C68DC4F3/sources/contracts/polymeebits.sol | A distinct URI (RFC 3986) for a given NFT. _tokenId Id for which we want uri. return _tokenId URI of _tokenId./ | function tokenURI(uint256 _tokenId) external view validNFToken(_tokenId) returns (string memory) {
}
| 856,164 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract WeathlPurchase is ERC721, ERC721Enumerable, ERC721Burnable, AccessControl {
using Counters for Counters.Counter;
struct Purchase {
address owner;
uint256 amount;
string token;
uint256 percentage;
}
mapping(uint => Purchase[]) purchases;
mapping(uint => mapping(address => uint256[])) ownedTokens;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
constructor() ERC721("Weathl Purchase", "WEATHL") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function safeMint(address _mintTo, address payer, uint256 amount, string memory token, uint256 percentage, uint _poolround) public onlyRole(MINTER_ROLE) returns (uint256) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(_mintTo, tokenId);
purchases[tokenId].push(Purchase(payer, amount, token, percentage));
ownedTokens[_poolround][payer].push(tokenId);
return tokenId;
}
function safeBurnAndModify(address sender, uint256 tokenId) public onlyRole(MINTER_ROLE) {
require(ownerOf(tokenId) == sender, "Invalid Owner");
purchases[tokenId].pop();
burn(tokenId);
}
function getOwnedTokens(address owner, uint _poolround) public view returns (uint256[] memory) {
return ownedTokens[_poolround][owner];
}
//Get Token Percentage
function GetTokenPercentage(address reciept) public returns (uint256){
return (purchases[tokenId][0].percentage);
}
function getPurchase(uint256 tokenId) public view onlyRole(MINTER_ROLE) returns (address, uint256, string memory, uint256) {
return (purchases[tokenId][0].owner, purchases[tokenId][0].amount, purchases[tokenId][0].token, purchases[tokenId][0].percentage);
// return purchases[tokenId][0];
}
function completeClaim(uint256 tokenId, uint256 _poolround, address a) public onlyRole(MINTER_ROLE) {
require(ownerOf(tokenId) == a, "Invalid Owner");
purchases[tokenId].pop();
ownedTokens[_poolround][a].pop();
}
function setPoolAddress(address poolAddress) public onlyRole(DEFAULT_ADMIN_ROLE){
_grantRole(MINTER_ROLE, poolAddress);
}
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, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| return purchases[tokenId][0]; | function getPurchase(uint256 tokenId) public view onlyRole(MINTER_ROLE) returns (address, uint256, string memory, uint256) {
return (purchases[tokenId][0].owner, purchases[tokenId][0].amount, purchases[tokenId][0].token, purchases[tokenId][0].percentage);
}
| 5,424,045 |
./partial_match/56/0xFe925F55dC810eFe505124698A30c356fd8d06bB/sources/ZethyrPancakeSwap.sol | Action::swapTokensForExactBNB/ get Token | function swapTokensForExactBNB(uint amountOut, uint amountInMax, address[] calldata path, address to)
external
returns (uint[] memory amounts)
{
amounts = cPSwapRouter.getAmountsIn(amountOut, path);
require(amounts[0] <= amountInMax, 'ZPancakeSwap::07:00');
require(amountInMax > 0, 'ZPancakeSwap::07:01');
require(amountOut > 0, 'ZPancakeSwap::07:02');
require(path.length == 2, 'ZPancakeSwap::07:03');
require(path[0] != address(0) && path[1] != address(0), 'ZPancakeSwap::07:04');
require(path[0] != to && path[1] != to, 'ZPancakeSwap::07:05');
require(IBEP20(path[0]).balanceOf(msg.sender) >= amountInMax, 'ZPancakeSwap::07:06');
uint256 _payback = SafeMath.sub(amountInMax, amounts[0]);
IBEP20(path[0]).transferFrom(msg.sender, address(this), amountInMax);
cPSwapRouter.swapTokensForExactETH(amountOut, amounts[0], path, to, now);
if (_payback > 0) {
IBEP20(path[0]).transfer(msg.sender, _payback);
}
cZSwapMemory.createSwapHistory(msg.sender, to, path[0], path[1], amountInMax, amountOut, _payback);
| 11,047,547 |
pragma solidity 0.4.18;
// File: contracts/libraries/PermissionsLib.sol
/*
Copyright 2017 Dharma 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.4.18;
/**
* Note(kayvon): these events are emitted by our PermissionsLib, but all contracts that
* depend on the library must also define the events in order for web3 clients to pick them up.
* This topic is discussed in greater detail here (under the section "Events and Libraries"):
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736
*/
contract PermissionEvents {
event Authorized(address indexed agent, string callingContext);
event AuthorizationRevoked(address indexed agent, string callingContext);
}
library PermissionsLib {
// TODO(kayvon): remove these events and inherit from PermissionEvents when libraries are
// capable of inheritance.
// See relevant github issue here: https://github.com/ethereum/solidity/issues/891
event Authorized(address indexed agent, string callingContext);
event AuthorizationRevoked(address indexed agent, string callingContext);
struct Permissions {
mapping (address => bool) authorized;
mapping (address => uint) agentToIndex; // ensures O(1) look-up
address[] authorizedAgents;
}
function authorize(
Permissions storage self,
address agent,
string callingContext
)
internal
{
require(isNotAuthorized(self, agent));
self.authorized[agent] = true;
self.authorizedAgents.push(agent);
self.agentToIndex[agent] = self.authorizedAgents.length - 1;
Authorized(agent, callingContext);
}
function revokeAuthorization(
Permissions storage self,
address agent,
string callingContext
)
internal
{
/* We only want to do work in the case where the agent whose
authorization is being revoked had authorization permissions in the
first place. */
require(isAuthorized(self, agent));
uint indexOfAgentToRevoke = self.agentToIndex[agent];
uint indexOfAgentToMove = self.authorizedAgents.length - 1;
address agentToMove = self.authorizedAgents[indexOfAgentToMove];
// Revoke the agent's authorization.
delete self.authorized[agent];
// Remove the agent from our collection of authorized agents.
self.authorizedAgents[indexOfAgentToRevoke] = agentToMove;
// Update our indices to reflect the above changes.
self.agentToIndex[agentToMove] = indexOfAgentToRevoke;
delete self.agentToIndex[agent];
// Clean up memory that's no longer being used.
delete self.authorizedAgents[indexOfAgentToMove];
self.authorizedAgents.length -= 1;
AuthorizationRevoked(agent, callingContext);
}
function isAuthorized(Permissions storage self, address agent)
internal
view
returns (bool)
{
return self.authorized[agent];
}
function isNotAuthorized(Permissions storage self, address agent)
internal
view
returns (bool)
{
return !isAuthorized(self, agent);
}
function getAuthorizedAgents(Permissions storage self)
internal
view
returns (address[])
{
return self.authorizedAgents;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/DebtRegistry.sol
/*
Copyright 2017 Dharma 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.4.18;
/**
* The DebtRegistry stores the parameters and beneficiaries of all debt agreements in
* Dharma protocol. It authorizes a limited number of agents to
* perform mutations on it -- those agents can be changed at any
* time by the contract's owner.
*
* Author: Nadav Hollander -- Github: nadavhollander
*/
contract DebtRegistry is Pausable, PermissionEvents {
using SafeMath for uint;
using PermissionsLib for PermissionsLib.Permissions;
struct Entry {
address version;
address beneficiary;
address underwriter;
uint underwriterRiskRating;
address termsContract;
bytes32 termsContractParameters;
uint issuanceBlockTimestamp;
}
// Primary registry mapping agreement IDs to their corresponding entries
mapping (bytes32 => Entry) internal registry;
// Maps debtor addresses to a list of their debts' agreement IDs
mapping (address => bytes32[]) internal debtorToDebts;
PermissionsLib.Permissions internal entryInsertPermissions;
PermissionsLib.Permissions internal entryEditPermissions;
string public constant INSERT_CONTEXT = "debt-registry-insert";
string public constant EDIT_CONTEXT = "debt-registry-edit";
event LogInsertEntry(
bytes32 indexed agreementId,
address indexed beneficiary,
address indexed underwriter,
uint underwriterRiskRating,
address termsContract,
bytes32 termsContractParameters
);
event LogModifyEntryBeneficiary(
bytes32 indexed agreementId,
address indexed previousBeneficiary,
address indexed newBeneficiary
);
modifier onlyAuthorizedToInsert() {
require(entryInsertPermissions.isAuthorized(msg.sender));
_;
}
modifier onlyAuthorizedToEdit() {
require(entryEditPermissions.isAuthorized(msg.sender));
_;
}
modifier onlyExtantEntry(bytes32 agreementId) {
require(doesEntryExist(agreementId));
_;
}
modifier nonNullBeneficiary(address beneficiary) {
require(beneficiary != address(0));
_;
}
/* Ensures an entry with the specified agreement ID exists within the debt registry. */
function doesEntryExist(bytes32 agreementId)
public
view
returns (bool exists)
{
return registry[agreementId].beneficiary != address(0);
}
/**
* Inserts a new entry into the registry, if the entry is valid and sender is
* authorized to make 'insert' mutations to the registry.
*/
function insert(
address _version,
address _beneficiary,
address _debtor,
address _underwriter,
uint _underwriterRiskRating,
address _termsContract,
bytes32 _termsContractParameters,
uint _salt
)
public
onlyAuthorizedToInsert
whenNotPaused
nonNullBeneficiary(_beneficiary)
returns (bytes32 _agreementId)
{
Entry memory entry = Entry(
_version,
_beneficiary,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
block.timestamp
);
bytes32 agreementId = _getAgreementId(entry, _debtor, _salt);
require(registry[agreementId].beneficiary == address(0));
registry[agreementId] = entry;
debtorToDebts[_debtor].push(agreementId);
LogInsertEntry(
agreementId,
entry.beneficiary,
entry.underwriter,
entry.underwriterRiskRating,
entry.termsContract,
entry.termsContractParameters
);
return agreementId;
}
/**
* Modifies the beneficiary of a debt issuance, if the sender
* is authorized to make 'modifyBeneficiary' mutations to
* the registry.
*/
function modifyBeneficiary(bytes32 agreementId, address newBeneficiary)
public
onlyAuthorizedToEdit
whenNotPaused
onlyExtantEntry(agreementId)
nonNullBeneficiary(newBeneficiary)
{
address previousBeneficiary = registry[agreementId].beneficiary;
registry[agreementId].beneficiary = newBeneficiary;
LogModifyEntryBeneficiary(
agreementId,
previousBeneficiary,
newBeneficiary
);
}
/**
* Adds an address to the list of agents authorized
* to make 'insert' mutations to the registry.
*/
function addAuthorizedInsertAgent(address agent)
public
onlyOwner
{
entryInsertPermissions.authorize(agent, INSERT_CONTEXT);
}
/**
* Adds an address to the list of agents authorized
* to make 'modifyBeneficiary' mutations to the registry.
*/
function addAuthorizedEditAgent(address agent)
public
onlyOwner
{
entryEditPermissions.authorize(agent, EDIT_CONTEXT);
}
/**
* Removes an address from the list of agents authorized
* to make 'insert' mutations to the registry.
*/
function revokeInsertAgentAuthorization(address agent)
public
onlyOwner
{
entryInsertPermissions.revokeAuthorization(agent, INSERT_CONTEXT);
}
/**
* Removes an address from the list of agents authorized
* to make 'modifyBeneficiary' mutations to the registry.
*/
function revokeEditAgentAuthorization(address agent)
public
onlyOwner
{
entryEditPermissions.revokeAuthorization(agent, EDIT_CONTEXT);
}
/**
* Returns the parameters of a debt issuance in the registry.
*
* TODO(kayvon): protect this function with our `onlyExtantEntry` modifier once the restriction
* on the size of the call stack has been addressed.
*/
function get(bytes32 agreementId)
public
view
returns(address, address, address, uint, address, bytes32, uint)
{
return (
registry[agreementId].version,
registry[agreementId].beneficiary,
registry[agreementId].underwriter,
registry[agreementId].underwriterRiskRating,
registry[agreementId].termsContract,
registry[agreementId].termsContractParameters,
registry[agreementId].issuanceBlockTimestamp
);
}
/**
* Returns the beneficiary of a given issuance
*/
function getBeneficiary(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns(address)
{
return registry[agreementId].beneficiary;
}
/**
* Returns the terms contract address of a given issuance
*/
function getTermsContract(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (address)
{
return registry[agreementId].termsContract;
}
/**
* Returns the terms contract parameters of a given issuance
*/
function getTermsContractParameters(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (bytes32)
{
return registry[agreementId].termsContractParameters;
}
/**
* Returns a tuple of the terms contract and its associated parameters
* for a given issuance
*/
function getTerms(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns(address, bytes32)
{
return (
registry[agreementId].termsContract,
registry[agreementId].termsContractParameters
);
}
/**
* Returns the timestamp of the block at which a debt agreement was issued.
*/
function getIssuanceBlockTimestamp(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (uint timestamp)
{
return registry[agreementId].issuanceBlockTimestamp;
}
/**
* Returns the list of agents authorized to make 'insert' mutations
*/
function getAuthorizedInsertAgents()
public
view
returns(address[])
{
return entryInsertPermissions.getAuthorizedAgents();
}
/**
* Returns the list of agents authorized to make 'modifyBeneficiary' mutations
*/
function getAuthorizedEditAgents()
public
view
returns(address[])
{
return entryEditPermissions.getAuthorizedAgents();
}
/**
* Returns the list of debt agreements a debtor is party to,
* with each debt agreement listed by agreement ID.
*/
function getDebtorsDebts(address debtor)
public
view
returns(bytes32[])
{
return debtorToDebts[debtor];
}
/**
* Helper function for computing the hash of a given issuance,
* and, in turn, its agreementId
*/
function _getAgreementId(Entry _entry, address _debtor, uint _salt)
internal
pure
returns(bytes32)
{
return keccak256(
_entry.version,
_debtor,
_entry.underwriter,
_entry.underwriterRiskRating,
_entry.termsContract,
_entry.termsContractParameters,
_salt
);
}
}
// File: contracts/TermsContract.sol
/*
Copyright 2017 Dharma 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.4.18;
interface TermsContract {
/// When called, the registerTermStart function registers the fact that
/// the debt agreement has begun. This method is called as a hook by the
/// DebtKernel when a debt order associated with `agreementId` is filled.
/// Method is not required to make any sort of internal state change
/// upon the debt agreement's start, but MUST return `true` in order to
/// acknowledge receipt of the transaction. If, for any reason, the
/// debt agreement stored at `agreementId` is incompatible with this contract,
/// MUST return `false`, which will cause the pertinent order fill to fail.
/// If this method is called for a debt agreement whose term has already begun,
/// must THROW. Similarly, if this method is called by any contract other
/// than the current DebtKernel, must THROW.
/// @param agreementId bytes32. The agreement id (issuance hash) of the debt agreement to which this pertains.
/// @param debtor address. The debtor in this particular issuance.
/// @return _success bool. Acknowledgment of whether
function registerTermStart(
bytes32 agreementId,
address debtor
) public returns (bool _success);
/// When called, the registerRepayment function records the debtor's
/// repayment, as well as any auxiliary metadata needed by the contract
/// to determine ex post facto the value repaid (e.g. current USD
/// exchange rate)
/// @param agreementId bytes32. The agreement id (issuance hash) of the debt agreement to which this pertains.
/// @param payer address. The address of the payer.
/// @param beneficiary address. The address of the payment's beneficiary.
/// @param unitsOfRepayment uint. The units-of-value repaid in the transaction.
/// @param tokenAddress address. The address of the token with which the repayment transaction was executed.
function registerRepayment(
bytes32 agreementId,
address payer,
address beneficiary,
uint256 unitsOfRepayment,
address tokenAddress
) public returns (bool _success);
/// Returns the cumulative units-of-value expected to be repaid by a given block timestamp.
/// Note this is not a constant function -- this value can vary on basis of any number of
/// conditions (e.g. interest rates can be renegotiated if repayments are delinquent).
/// @param agreementId bytes32. The agreement id (issuance hash) of the debt agreement to which this pertains.
/// @param timestamp uint. The timestamp of the block for which repayment expectation is being queried.
/// @return uint256 The cumulative units-of-value expected to be repaid by the time the given timestamp lapses.
function getExpectedRepaymentValue(
bytes32 agreementId,
uint256 timestamp
) public view returns (uint256);
/// Returns the cumulative units-of-value repaid by the point at which this method is called.
/// @param agreementId bytes32. The agreement id (issuance hash) of the debt agreement to which this pertains.
/// @return uint256 The cumulative units-of-value repaid up until now.
function getValueRepaidToDate(
bytes32 agreementId
) public view returns (uint256);
/**
* A method that returns a Unix timestamp representing the end of the debt agreement's term.
* contract.
*/
function getTermEndTimestamp(
bytes32 _agreementId
) public view returns (uint);
}
// File: contracts/TokenRegistry.sol
/**
* The TokenRegistry is a basic registry mapping token symbols
* to their known, deployed addresses on the current blockchain.
*
* Note that the TokenRegistry does *not* mediate any of the
* core protocol's business logic, but, rather, is a helpful
* utility for Terms Contracts to use in encoding, decoding, and
* resolving the addresses of currently deployed tokens.
*
* At this point in time, administration of the Token Registry is
* under Dharma Labs' control. With more sophisticated decentralized
* governance mechanisms, we intend to shift ownership of this utility
* contract to the Dharma community.
*/
contract TokenRegistry is Ownable {
mapping (bytes32 => TokenAttributes) public symbolHashToTokenAttributes;
string[256] public tokenSymbolList;
uint8 public tokenSymbolListLength;
struct TokenAttributes {
// The ERC20 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. "Canonical Wrapped Ether"
string name;
// The number of digits that come after the decimal place when displaying token value.
uint8 numDecimals;
}
/**
* Maps the given symbol to the given token attributes.
*/
function setTokenAttributes(
string _symbol,
address _tokenAddress,
string _tokenName,
uint8 _numDecimals
)
public onlyOwner
{
bytes32 symbolHash = keccak256(_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.numDecimals = _numDecimals;
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.numDecimals = _numDecimals;
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 _symbol) public view returns (address) {
bytes32 symbolHash = keccak256(_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.
*
* This is a useful utility for compactly encoding the address of a token into a
* TermsContractParameters string -- by encoding a token by its index in a
* a 256 slot array, we can represent a token by a 1 byte uint instead of a 20 byte address.
*/
function getTokenAddressByIndex(uint _index) public view returns (address) {
string storage symbol = tokenSymbolList[_index];
return 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 _symbol) public view returns (uint) {
bytes32 symbolHash = keccak256(_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) {
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 _symbol) public view returns (string) {
bytes32 symbolHash = keccak256(_symbol);
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.name;
}
/**
* Given the symbol for a token, returns the number of decimals as provided in
* the associated TokensAttribute struct.
*
* Example:
* getNumDecimalsFromSymbol("REP");
* => 18
*/
function getNumDecimalsFromSymbol(string _symbol) public view returns (uint8) {
bytes32 symbolHash = keccak256(_symbol);
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.numDecimals;
}
/**
* Given the index for a token in the registry, returns the number of decimals as provided in
* the associated TokensAttribute struct.
*
* Example:
* getNumDecimalsByIndex(1);
* => 18
*/
function getNumDecimalsByIndex(uint _index) public view returns (uint8) {
string memory symbol = getTokenSymbolByIndex(_index);
return getNumDecimalsFromSymbol(symbol);
}
/**
* 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);
* => "Canonical Wrapped Ether"
*/
function getTokenNameByIndex(uint _index) public view returns (string) {
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, the token's name, and the number of decimals.
*
* Example:
* getTokenAttributesBySymbol("WETH");
* => ["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", 1, "Canonical Wrapped Ether", 18]
*/
function getTokenAttributesBySymbol(string _symbol)
public
view
returns (
address,
uint,
string,
uint
)
{
bytes32 symbolHash = keccak256(_symbol);
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return (
attributes.tokenAddress,
attributes.tokenIndex,
attributes.name,
attributes.numDecimals
);
}
/**
* Given the index for a token in the registry, returns a tuple containing the token's address,
* the token's symbol, the token's name, and the number of decimals.
*
* Example:
* getTokenAttributesByIndex(1);
* => ["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "WETH", "Canonical Wrapped Ether", 18]
*/
function getTokenAttributesByIndex(uint _index)
public
view
returns (
address,
string,
string,
uint8
)
{
string memory symbol = getTokenSymbolByIndex(_index);
bytes32 symbolHash = keccak256(symbol);
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return (
attributes.tokenAddress,
symbol,
attributes.name,
attributes.numDecimals
);
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/TokenTransferProxy.sol
/*
Copyright 2017 Dharma 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.4.18;
/**
* The TokenTransferProxy is a proxy contract for transfering principal
* and fee payments and repayments between agents and keepers in the Dharma
* ecosystem. It is decoupled from the DebtKernel in order to make upgrades to the
* protocol contracts smoother -- if the DebtKernel or RepyamentRouter is upgraded to a new contract,
* creditors will not have to grant new transfer approvals to a new contract's address.
*
* Author: Nadav Hollander -- Github: nadavhollander
*/
contract TokenTransferProxy is Pausable, PermissionEvents {
using PermissionsLib for PermissionsLib.Permissions;
PermissionsLib.Permissions internal tokenTransferPermissions;
string public constant CONTEXT = "token-transfer-proxy";
/**
* Add address to list of agents authorized to initiate `transferFrom` calls
*/
function addAuthorizedTransferAgent(address _agent)
public
onlyOwner
{
tokenTransferPermissions.authorize(_agent, CONTEXT);
}
/**
* Remove address from list of agents authorized to initiate `transferFrom` calls
*/
function revokeTransferAgentAuthorization(address _agent)
public
onlyOwner
{
tokenTransferPermissions.revokeAuthorization(_agent, CONTEXT);
}
/**
* Return list of agents authorized to initiate `transferFrom` calls
*/
function getAuthorizedTransferAgents()
public
view
returns (address[] authorizedAgents)
{
return tokenTransferPermissions.getAuthorizedAgents();
}
/**
* Transfer specified token amount from _from address to _to address on give token
*/
function transferFrom(
address _token,
address _from,
address _to,
uint _amount
)
public
returns (bool _success)
{
require(tokenTransferPermissions.isAuthorized(msg.sender));
return ERC20(_token).transferFrom(_from, _to, _amount);
}
}
// File: contracts/Collateralizer.sol
/*
Copyright 2017 Dharma 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.4.18;
/**
* Contains functionality for collateralizing assets, by transferring them from
* a debtor address to this contract as a custodian.
*
* Authors (in no particular order): nadavhollander, saturnial, jdkanani, graemecode
*/
contract Collateralizer is Pausable, PermissionEvents {
using PermissionsLib for PermissionsLib.Permissions;
using SafeMath for uint;
address public debtKernelAddress;
DebtRegistry public debtRegistry;
TokenRegistry public tokenRegistry;
TokenTransferProxy public tokenTransferProxy;
// Collateralizer here refers to the owner of the asset that is being collateralized.
mapping(bytes32 => address) public agreementToCollateralizer;
PermissionsLib.Permissions internal collateralizationPermissions;
uint public constant SECONDS_IN_DAY = 24*60*60;
string public constant CONTEXT = "collateralizer";
event CollateralLocked(
bytes32 indexed agreementID,
address indexed token,
uint amount
);
event CollateralReturned(
bytes32 indexed agreementID,
address indexed collateralizer,
address token,
uint amount
);
event CollateralSeized(
bytes32 indexed agreementID,
address indexed beneficiary,
address token,
uint amount
);
modifier onlyAuthorizedToCollateralize() {
require(collateralizationPermissions.isAuthorized(msg.sender));
_;
}
function Collateralizer(
address _debtKernel,
address _debtRegistry,
address _tokenRegistry,
address _tokenTransferProxy
) public {
debtKernelAddress = _debtKernel;
debtRegistry = DebtRegistry(_debtRegistry);
tokenRegistry = TokenRegistry(_tokenRegistry);
tokenTransferProxy = TokenTransferProxy(_tokenTransferProxy);
}
/**
* Transfers collateral from the debtor to the current contract, as custodian.
*
* @param agreementId bytes32 The debt agreement's ID
* @param collateralizer address The owner of the asset being collateralized
*/
function collateralize(
bytes32 agreementId,
address collateralizer
)
public
onlyAuthorizedToCollateralize
whenNotPaused
returns (bool _success)
{
// The token in which collateral is denominated
address collateralToken;
// The amount being put up for collateral
uint collateralAmount;
// The number of days a debtor has after a debt enters default
// before their collateral is eligible for seizure.
uint gracePeriodInDays;
// The terms contract according to which this asset is being collateralized.
TermsContract termsContract;
// Fetch all relevant collateralization parameters
(
collateralToken,
collateralAmount,
gracePeriodInDays,
termsContract
) = retrieveCollateralParameters(agreementId);
require(termsContract == msg.sender);
require(collateralAmount > 0);
require(collateralToken != address(0));
/*
Ensure that the agreement has not already been collateralized.
If the agreement has already been collateralized, this check will fail
because any valid collateralization must have some sort of valid
address associated with it as a collateralizer. Given that it is impossible
to send transactions from address 0x0, this check will only fail
when the agreement is already collateralized.
*/
require(agreementToCollateralizer[agreementId] == address(0));
ERC20 erc20token = ERC20(collateralToken);
address custodian = address(this);
/*
The collateralizer must have sufficient balance equal to or greater
than the amount being put up for collateral.
*/
require(erc20token.balanceOf(collateralizer) >= collateralAmount);
/*
The proxy must have an allowance granted by the collateralizer equal
to or greater than the amount being put up for collateral.
*/
require(erc20token.allowance(collateralizer, tokenTransferProxy) >= collateralAmount);
// store collaterallizer in mapping, effectively demarcating that the
// agreement is now collateralized.
agreementToCollateralizer[agreementId] = collateralizer;
// the collateral must be successfully transferred to this contract, via a proxy.
require(tokenTransferProxy.transferFrom(
erc20token,
collateralizer,
custodian,
collateralAmount
));
// emit event that collateral has been secured.
CollateralLocked(agreementId, collateralToken, collateralAmount);
return true;
}
/**
* Returns collateral to the debt agreement's original collateralizer
* if and only if the debt agreement's term has lapsed and
* the total expected repayment value has been repaid.
*
* @param agreementId bytes32 The debt agreement's ID
*/
function returnCollateral(
bytes32 agreementId
)
public
whenNotPaused
{
// The token in which collateral is denominated
address collateralToken;
// The amount being put up for collateral
uint collateralAmount;
// The number of days a debtor has after a debt enters default
// before their collateral is eligible for seizure.
uint gracePeriodInDays;
// The terms contract according to which this asset is being collateralized.
TermsContract termsContract;
// Fetch all relevant collateralization parameters.
(
collateralToken,
collateralAmount,
gracePeriodInDays,
termsContract
) = retrieveCollateralParameters(agreementId);
// Ensure a valid form of collateral is tied to this agreement id
require(collateralAmount > 0);
require(collateralToken != address(0));
// Withdrawal can only occur if the collateral has yet to be withdrawn.
// When we withdraw collateral, we reset the collateral agreement
// in a gas-efficient manner by resetting the address of the collateralizer to 0
require(agreementToCollateralizer[agreementId] != address(0));
// Ensure that the debt is not in a state of default
require(
termsContract.getExpectedRepaymentValue(
agreementId,
termsContract.getTermEndTimestamp(agreementId)
) <= termsContract.getValueRepaidToDate(agreementId)
);
// determine collateralizer of the collateral.
address collateralizer = agreementToCollateralizer[agreementId];
// Mark agreement's collateral as withdrawn by setting the agreement's
// collateralizer to 0x0.
delete agreementToCollateralizer[agreementId];
// transfer the collateral this contract was holding in escrow back to collateralizer.
require(
ERC20(collateralToken).transfer(
collateralizer,
collateralAmount
)
);
// log the return event.
CollateralReturned(
agreementId,
collateralizer,
collateralToken,
collateralAmount
);
}
/**
* Seizes the collateral from the given debt agreement and
* transfers it to the debt agreement's current beneficiary
* (i.e. the person who "owns" the debt).
*
* @param agreementId bytes32 The debt agreement's ID
*/
function seizeCollateral(
bytes32 agreementId
)
public
whenNotPaused
{
// The token in which collateral is denominated
address collateralToken;
// The amount being put up for collateral
uint collateralAmount;
// The number of days a debtor has after a debt enters default
// before their collateral is eligible for seizure.
uint gracePeriodInDays;
// The terms contract according to which this asset is being collateralized.
TermsContract termsContract;
// Fetch all relevant collateralization parameters
(
collateralToken,
collateralAmount,
gracePeriodInDays,
termsContract
) = retrieveCollateralParameters(agreementId);
// Ensure a valid form of collateral is tied to this agreement id
require(collateralAmount > 0);
require(collateralToken != address(0));
// Seizure can only occur if the collateral has yet to be withdrawn.
// When we withdraw collateral, we reset the collateral agreement
// in a gas-efficient manner by resetting the address of the collateralizer to 0
require(agreementToCollateralizer[agreementId] != address(0));
// Ensure debt is in a state of default when we account for the
// specified "grace period". We do this by checking whether the
// *current* value repaid to-date exceeds the expected repayment value
// at the point of time at which the grace period would begin if it ended
// now. This crucially relies on the assumption that both expected repayment value
/// and value repaid to date monotonically increase over time
require(
termsContract.getExpectedRepaymentValue(
agreementId,
timestampAdjustedForGracePeriod(gracePeriodInDays)
) > termsContract.getValueRepaidToDate(agreementId)
);
// Mark agreement's collateral as withdrawn by setting the agreement's
// collateralizer to 0x0.
delete agreementToCollateralizer[agreementId];
// determine beneficiary of the seized collateral.
address beneficiary = debtRegistry.getBeneficiary(agreementId);
// transfer the collateral this contract was holding in escrow to beneficiary.
require(
ERC20(collateralToken).transfer(
beneficiary,
collateralAmount
)
);
// log the seizure event.
CollateralSeized(
agreementId,
beneficiary,
collateralToken,
collateralAmount
);
}
/**
* Adds an address to the list of agents authorized
* to invoke the `collateralize` function.
*/
function addAuthorizedCollateralizeAgent(address agent)
public
onlyOwner
{
collateralizationPermissions.authorize(agent, CONTEXT);
}
/**
* Removes an address from the list of agents authorized
* to invoke the `collateralize` function.
*/
function revokeCollateralizeAuthorization(address agent)
public
onlyOwner
{
collateralizationPermissions.revokeAuthorization(agent, CONTEXT);
}
/**
* Returns the list of agents authorized to invoke the 'collateralize' function.
*/
function getAuthorizedCollateralizeAgents()
public
view
returns(address[])
{
return collateralizationPermissions.getAuthorizedAgents();
}
/**
* Unpacks collateralization-specific parameters from their tightly-packed
* representation in a terms contract parameter string.
*
* For collateralized terms contracts, we reserve the lowest order 108 bits
* of the terms contract parameters for parameters relevant to collateralization.
*
* Contracts that inherit from the Collateralized terms contract
* can encode whichever parameter schema they please in the remaining
* space of the terms contract parameters.
* The 108 bits are encoded as follows (from higher order bits to lower order bits):
*
* 8 bits - Collateral Token (encoded by its unsigned integer index in the TokenRegistry contract)
* 92 bits - Collateral Amount (encoded as an unsigned integer)
* 8 bits - Grace Period* Length (encoded as an unsigned integer)
*
* * = The "Grace" Period is the number of days a debtor has between
* when they fall behind on an expected payment and when their collateral
* can be seized by the creditor.
*/
function unpackCollateralParametersFromBytes(bytes32 parameters)
public
pure
returns (uint, uint, uint)
{
// The first byte of the 108 reserved bits represents the collateral token.
bytes32 collateralTokenIndexShifted =
parameters & 0x0000000000000000000000000000000000000ff0000000000000000000000000;
// The subsequent 92 bits represents the collateral amount, as denominated in the above token.
bytes32 collateralAmountShifted =
parameters & 0x000000000000000000000000000000000000000fffffffffffffffffffffff00;
// We bit-shift these values, respectively, 100 bits and 8 bits right using
// mathematical operations, so that their 32 byte integer counterparts
// correspond to the intended values packed in the 32 byte string
uint collateralTokenIndex = uint(collateralTokenIndexShifted) / 2 ** 100;
uint collateralAmount = uint(collateralAmountShifted) / 2 ** 8;
// The last byte of the parameters represents the "grace period" of the loan,
// as defined in terms of days.
// Since this value takes the rightmost place in the parameters string,
// we do not need to bit-shift it.
bytes32 gracePeriodInDays =
parameters & 0x00000000000000000000000000000000000000000000000000000000000000ff;
return (
collateralTokenIndex,
collateralAmount,
uint(gracePeriodInDays)
);
}
function timestampAdjustedForGracePeriod(uint gracePeriodInDays)
public
view
returns (uint)
{
return block.timestamp.sub(
SECONDS_IN_DAY.mul(gracePeriodInDays)
);
}
function retrieveCollateralParameters(bytes32 agreementId)
internal
view
returns (
address _collateralToken,
uint _collateralAmount,
uint _gracePeriodInDays,
TermsContract _termsContract
)
{
address termsContractAddress;
bytes32 termsContractParameters;
// Pull the terms contract and associated parameters for the agreement
(termsContractAddress, termsContractParameters) = debtRegistry.getTerms(agreementId);
uint collateralTokenIndex;
uint collateralAmount;
uint gracePeriodInDays;
// Unpack terms contract parameters in order to get collateralization-specific params
(
collateralTokenIndex,
collateralAmount,
gracePeriodInDays
) = unpackCollateralParametersFromBytes(termsContractParameters);
// Resolve address of token associated with this agreement in token registry
address collateralTokenAddress = tokenRegistry.getTokenAddressByIndex(collateralTokenIndex);
return (
collateralTokenAddress,
collateralAmount,
gracePeriodInDays,
TermsContract(termsContractAddress)
);
}
} | Given the index for a token in the registry, returns the number of decimals as provided in the associated TokensAttribute struct. Example: getNumDecimalsByIndex(1); => 18/ | function getNumDecimalsByIndex(uint _index) public view returns (uint8) {
string memory symbol = getTokenSymbolByIndex(_index);
return getNumDecimalsFromSymbol(symbol);
}
| 5,474,447 |
/*
RE-Cent OffChain-Transactions/Payment Channels Smart Contract v.1.0.0
Author: Giannis Zarifis <[email protected]>
*/
pragma solidity ^0.5.0;
import "./RecentBlockchain.sol";
//Smart Contract for P2P Payment channels and Relayers Payment channels. Inherits RecentBlockchain
contract PaymentChannels is RecentBlockchain {
constructor() public {}
//P2P channels structure
struct Channel {
//Channel hash/Id
bytes32 id;
//Channel Owner
address payable sender;
//Recipient Peer
address payable recipient;
//Lock until Timestamp
uint256 lockUntil;
//Remaining Balance
uint256 balance;
//State Open or Close
bool isOpen;
}
//The already paid amount for a P2P Payment channel given a nonce
mapping(bytes32 => mapping(bytes32 => uint256)) noncePaidAmount;
//The P2P Payment channel Id for a User channel number
mapping(address => mapping(uint256 => bytes32)) userChannels;
//The P2P channel for a channel Id
mapping(bytes32 => Channel) channels;
//The number of a User total number of channels
mapping(address => uint256) numberOfUserChannels;
// Notifies that a new Channel was opened
event ChannelOpened(
bytes32 id,
address indexed sender,
address indexed recipient,
uint256 amount
);
// Notifies for a deposit to a Channel
event DepositToChannel(bytes32 id, address indexed sender, uint256 amount);
// Notifies for Channel closed
event ChannelClosed(bytes32 id, address indexed sender, uint256 amount);
// Notifies for Off-chain transaction finalized
event P2POffChainTransaction(
bytes32 indexed channelId,
address indexed sender,
address indexed recipient,
uint256 recipientAmount
);
//Open a new P2P Payment channel
//The first Peer(Channel Owner) is the Tx signer address
//The secord Peer is the recipient address
//The locked amount is the coins transfered to smart contract (msg.sender)
//Locks the coins for the lockTimeInDays days from now
function openChannel(address payable recipient, uint256 lockTimeInDays)
public
payable
{
//Amount to be locked should be greater than zero
require(msg.value > 0);
//The 2 Peers should be different addresses
require(recipient != msg.sender);
Channel memory newChannel;
//Channel Id by hashing the 2 peers and now timestamp
newChannel.id = keccak256(abi.encodePacked(msg.sender, recipient, now));
//Check if there is an already an opened channel for the recipient that has been mined previously on the same Block
require(!channels[newChannel.id].isOpen, "Channel Id already exists.");
//Store the Channel Id on Owner's number of opened channels. Initially 0
userChannels[msg.sender][numberOfUserChannels[msg.sender]] = newChannel
.id;
//Increase the number of Owner number of opened channels by 1
numberOfUserChannels[msg.sender] += 1;
//Setup the number of locked Coins, the Peers and lock until Timestamp
newChannel.balance = msg.value;
newChannel.sender = msg.sender;
newChannel.recipient = recipient;
newChannel.isOpen = true;
newChannel.lockUntil = now + lockTimeInDays * 1 days;
//Setup the channel on storage
channels[newChannel.id] = newChannel;
//Notify for the channel creation
emit ChannelOpened(newChannel.id, msg.sender, recipient, msg.value);
}
//Increase the number of locked coins for a Channel Id, extend the lock until Timestamp by increaseLckTimeInDays days
function depositToChannel(bytes32 id, uint256 increaseLckTimeInDays)
public
payable
{
//Extra Amount should be greater than zero
require(msg.value > 0);
//Channel Owner should be the Tx signer
require(
channels[id].sender == msg.sender,
"Message signer isn't the owner of channel"
);
//The extend number of days should be greater than zero
require(increaseLckTimeInDays >= 0);
//The Channel should be in Open State
require(channels[id].isOpen);
//Setup the new locked amount balance and lock until Timestamp
channels[id].balance += msg.value;
channels[id].lockUntil =
channels[id].lockUntil +
increaseLckTimeInDays *
1 days;
//Notify for the Deposit on an existing Channel
emit DepositToChannel(id, msg.sender, msg.value);
}
//Closes a Channel by releasing the remaining locked coins to Owner
function closeChannel(bytes32 id) public {
//Check that locked coins balance is grater than zero
require(channels[id].balance > 0, "Insufficient balance");
//Channel Owner should be the Tx signer
require(
channels[id].sender == msg.sender,
"Message signer isn't the owner of channel"
);
//The lock until period should be in the past
require(channels[id].lockUntil < now, "Balance is locked");
//Calculate and transfer the remaining balance to Owner address, Reset the balance, Close the Channel
uint256 amount = channels[id].balance;
channels[id].balance = 0;
channels[id].isOpen = false;
msg.sender.transfer(amount);
//Notify for the channel termination
emit ChannelClosed(id, msg.sender, amount);
}
//Settle a P2P Offchain Transaction
// h is the hash of signature
// r and s are outputs of the ECDSA signature
// v is the recovery id
// channelId is the P2P Channel Id
// The P2P nonce for the Channel Id
// The amount to be released from locked to recipient address
function finalizeOffchainP2PTransaction(
bytes32 h,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 channelId,
bytes32 nonce,
uint256 amount
) public {
//Calculate hash of input arguments channelId, nonce and amount
bytes32 proof = keccak256(abi.encodePacked(channelId, nonce, amount));
//The hash of input arguments should be equal with provided Offcain transaction Hash(Parameter h)
require(
proof == h,
"Off-chain transaction hash does't match with payload"
);
//Recover the Offcain transaction Signer using ECDA public key Recovery
address signer = ecrecover(h, v, r, s);
//Signer of the Tx should be the Owner of P2P Channel
require(
signer == channels[channelId].sender,
"Signer should be the channel Owner"
);
//Check the the requested amount is greater than any previously paid for the same nonce
require(
noncePaidAmount[channelId][nonce] < amount,
"Requested amount should be greater than the previous finalized for P2P content transaction"
);
//The delta betwwen the requested amount minus any previously paid for the same nonce(This is the amount will be transfer to recipient address)
uint256 amountToBeTransferred = amount -
noncePaidAmount[channelId][nonce];
//Setup the already paid amount for the channel given a nonce
noncePaidAmount[channelId][nonce] = amount;
//Check the existing Channel balance is sufficient
require(
channels[channelId].balance >= amountToBeTransferred,
"Insufficient balance"
);
//Reduce the existing Channel balance
channels[channelId].balance -= amountToBeTransferred;
//Transfer the Coins to recipient
address payable channelRecipient = channels[channelId].recipient;
channelRecipient.transfer(amountToBeTransferred);
//Notify for Offchain Tx settlement
emit P2POffChainTransaction(
channelId,
signer,
channelRecipient,
amountToBeTransferred
);
}
//Return the Channel Id by a given Peer Channel number
function getChannelId(uint256 userChannelId) public view returns (bytes32) {
return userChannels[msg.sender][userChannelId];
}
//Return the total number of Channels of a Peer
function getUserTotalChannels() public view returns (uint256) {
return numberOfUserChannels[msg.sender];
}
//The Relayer Payment Channel structure
struct Relayer {
//Relayer name
string name;
//Relayer Owner address
address payable owner;
//Relayer Offchain Endpoint URL that expose the Relayer API
string domain;
//Max allowed number of Peers(Depositors) based on requested Relayer license
uint256 maxUsers;
//Max allowed number of Coins(Deposits) based on requested Relayer license
uint256 maxCoins;
//Max allowed Offcain transactions throughput per 100000 Blocks based on requested Relayer license
uint256 maxTxThroughput;
//Current number of Peers(Depositors)
uint256 currentUsers;
//Current deposited Coins
uint256 currentCoins;
//Current used Offcain transactions throughput per 100000 Blocks
uint256 currentTxThroughput;
//Excepted Delay of an Offchain transaction settlement in number of Blocks
uint256 offchainTxDelay;
//Relayer fee(Thousands percent)
uint256 fee;
//Remaining Releayer penalty funds
uint256 remainingPenaltyFunds;
}
//Total Releayers for Epoch
mapping(uint256 => uint256) public relayersCounter;
//Relayer for epoch and Index
mapping(uint256 => mapping(uint256 => Relayer)) public relayers;
//The index of a Relayer for Epoch and Relayer Owner address. Index starts from value of 1
mapping(uint256 => mapping(address => uint256)) public epochRelayerIndex;
// Notify for a new Relayer as candidate
event RelayerProposed(
uint256 indexed epoch,
address indexed relayer,
string domain,
address indexed owner,
string name,
uint256 fee,
uint256 offchainTxDelay
);
// Notify for Relayer updated
event RelayerUpdated(
uint256 indexed epoch,
address indexed relayer,
string domain,
string name,
uint256 fee,
uint256 offchainTxDelay
);
// Notify for Relayer withdrawal of penalty funds
event RelayerWithdrawFunds(
uint256 indexed epoch,
address indexed relayer,
uint256 amount
);
//Called by a Relayer that requests a new license for an upcoming Epoch
//targetEpoch is the requested Epoch, usually Current Epoch + 1
//domain is the Relayer Offchain Endpoint URL that expose the Relayer API
//name is Relayer name
//fee is the Relayer fee(Thousands percent)
//maxUsers is the requested max number of Peers(Depositors)
//maxCoins is the requested max Coins could be deposited by Peers(Total Deposits)
//maxTxThroughput is the requested max allowed Offcain transactions throughput per 100000 Blocks
//offchainTxDelay is the expected settlement delay in Blocks
function requestRelayerLicense(
uint256 targetEpoch,
string memory domain,
string memory name,
uint256 fee,
uint256 maxUsers,
uint256 maxCoins,
uint256 maxTxThroughput,
uint256 offchainTxDelay
) public payable {
//If the requested isn't the initial Epoch(0)
//Check that election is open
//Check that requested is upcoming
if (targetEpoch > 1) {
require(
block.number < getCurrentRelayersElectionEnd(),
"Relayers election period has passed"
);
require(
targetEpoch > getCurrentEpoch(),
"Target epoch should be greater than current"
);
}
//Check for the validity of provided input parameters
require(maxUsers > 0, "maxUsers should be greater than 0");
require(maxCoins > 0, "maxCoins should be greater than 0");
require(
maxTxThroughput > 0,
"maxTxThroughput should be greater than 0"
);
require(
offchainTxDelay > 0,
"offchainTxDelay should be greater than 0"
);
require(fee < 1000, "Fee should be lower than 1000");
//Calculate the Coins required for lock by Relayer based on requested license
uint256 requiredAmount = getFundRequiredForRelayer(
maxUsers,
maxCoins,
maxTxThroughput
);
//Check that at least the Coins required are transfered to be locked
require(requiredAmount <= msg.value, "Invalid required amount");
//Check that there isn't any existing Relayer(Owner) license request for the requested Epoch
require(
epochRelayerIndex[targetEpoch][msg.sender] == 0,
"Already registered Relayer as candidate"
);
//Get the number of licenses requested for the Epoch
uint256 currentRelayersNumber = relayersCounter[targetEpoch];
//If current number of licenses exceeds the max allowed number lookup for a Relayer to be replaced
//Else place the requestor on list
if (currentRelayersNumber >= maximumRelayersNumber) {
address payable toBeReplacedRelayer = address(0);
uint256 toBeReplacedRelayerIndex = 0;
for (uint256 i = 1; i <= currentRelayersNumber; i++) {
//1st Relayer with lower funds is choosed to be replaced
if (
relayers[targetEpoch][i].remainingPenaltyFunds < msg.value
) {
toBeReplacedRelayer = address(
uint160(relayers[targetEpoch][i].owner)
);
toBeReplacedRelayerIndex = i;
break;
}
}
//If no Relayer found to be replaced Revert Transaction
if (toBeReplacedRelayer == address(0)) {
revert("Relayers list is full");
}
//Else the Replace the found Relayer with the requestor and transfer the locked funds back to his address
uint256 refund = relayers[targetEpoch][toBeReplacedRelayerIndex]
.remainingPenaltyFunds;
epochRelayerIndex[targetEpoch][toBeReplacedRelayer] = 0;
relayers[targetEpoch][toBeReplacedRelayerIndex].fee = fee;
relayers[targetEpoch][toBeReplacedRelayerIndex].maxUsers = maxUsers;
relayers[targetEpoch][toBeReplacedRelayerIndex].maxCoins = maxCoins;
relayers[targetEpoch][toBeReplacedRelayerIndex]
.maxTxThroughput = maxTxThroughput;
relayers[targetEpoch][toBeReplacedRelayerIndex]
.offchainTxDelay = offchainTxDelay;
relayers[targetEpoch][toBeReplacedRelayerIndex]
.remainingPenaltyFunds = requiredAmount;
relayers[targetEpoch][toBeReplacedRelayerIndex].name = name;
relayers[targetEpoch][toBeReplacedRelayerIndex].domain = domain;
relayers[targetEpoch][toBeReplacedRelayerIndex].owner = msg.sender;
epochRelayerIndex[targetEpoch][msg
.sender] = toBeReplacedRelayerIndex;
toBeReplacedRelayer.transfer(refund);
} else {
relayersCounter[targetEpoch]++;
relayers[targetEpoch][relayersCounter[targetEpoch]].fee = fee;
relayers[targetEpoch][relayersCounter[targetEpoch]]
.maxUsers = maxUsers;
relayers[targetEpoch][relayersCounter[targetEpoch]]
.maxCoins = maxCoins;
relayers[targetEpoch][relayersCounter[targetEpoch]]
.maxTxThroughput = maxTxThroughput;
relayers[targetEpoch][relayersCounter[targetEpoch]]
.offchainTxDelay = offchainTxDelay;
relayers[targetEpoch][relayersCounter[targetEpoch]]
.remainingPenaltyFunds = requiredAmount;
relayers[targetEpoch][relayersCounter[targetEpoch]].name = name;
relayers[targetEpoch][relayersCounter[targetEpoch]].domain = domain;
relayers[targetEpoch][relayersCounter[targetEpoch]].owner = msg
.sender;
epochRelayerIndex[targetEpoch][msg
.sender] = relayersCounter[targetEpoch];
}
//Notify for License request
emit RelayerProposed(
targetEpoch,
msg.sender,
domain,
msg.sender,
name,
fee,
offchainTxDelay
);
}
function testHashing(bytes32 id, string memory domain)
public
pure
returns (
bool,
bytes32,
bytes32
)
{
bytes32 lid = keccak256(abi.encodePacked(domain));
return (lid == id, id, lid);
}
//Update domain, name, fees, expected Tx daley for the requested Epoch of an existing Relayer
function updateRelayer(
uint256 targetEpoch,
string memory domain,
string memory name,
uint256 fee,
uint256 offchainTxDelay
) public {
uint256 index = epochRelayerIndex[targetEpoch][msg.sender];
//Check that Relayer is in list
require(index > 0, "Relayer not found");
//Check other input parameters
require(fee < 1000, "Fee should be lower than 1000");
require(
offchainTxDelay > 0,
"offchainTxDelay should be greater than 0"
);
//Setup new properties
relayers[targetEpoch][index].domain = domain;
relayers[targetEpoch][index].name = name;
relayers[targetEpoch][index].fee = fee;
relayers[targetEpoch][index].offchainTxDelay = offchainTxDelay;
//Notify Relayer updated
emit RelayerUpdated(
targetEpoch,
msg.sender,
domain,
name,
fee,
offchainTxDelay
);
}
//Withdraw Relayer locked funds for a previous Epoch
function relayerWithdrawPenaltyFunds(uint256 targetEpoch) public {
uint256 index = epochRelayerIndex[targetEpoch][msg.sender];
//Check that Relayer is in list
require(index > 0, "Relayer not found");
uint256 currentEpoch = getCurrentEpoch();
//Requested Epoch should be less than Previous Epoch
require(
targetEpoch < currentEpoch - 1,
"Current epoch should be lower than requested epoch"
);
//Transfer the remaining funds to Relayer Owner address
uint256 remainingAmount = relayers[targetEpoch][index]
.remainingPenaltyFunds;
require(remainingAmount > 0, "Insufficient balance");
relayers[targetEpoch][index].remainingPenaltyFunds = 0;
msg.sender.transfer(remainingAmount);
//Notify for Relayer withdrawal
emit RelayerWithdrawFunds(targetEpoch, msg.sender, remainingAmount);
}
//User Relayer Deposit structure
struct DepositOnRelayer {
//Lock funds until Block
uint256 lockUntilBlock;
//The remaining user balance
uint256 balance;
}
//Deposit of a User
mapping(address => mapping(address => DepositOnRelayer))
public userDepositOnRelayer;
//Amount settled for a user to beneficiary Offchain payment given a nonce and a Relayer
mapping(address => mapping(address => mapping(address => mapping(bytes32 => uint256))))
public userToBeneficiaryFinalizedAmountForNonce;
//Notify for user deposit on Relayer
event UserDeposit(
address indexed relayer,
address indexed user,
uint256 amount
);
//Notify for user withdraw on Relayer
event UserWithdraw(
address indexed relayer,
address indexed user,
uint256 amount
);
//Notify for Off-chain transaction finalized
event RelayedOffChainTransaction(
address indexed relayer,
address indexed user,
address indexed beneficiary,
uint256 relayerFee,
uint256 beneficiaryAmount,
bool isPayedFromPenaltyFunds
);
//Deposit to a Relayer
//relayerId is the Relayer Owner address
//lockUntilBlock is the Block number that funds are locked
function depositToRelayer(address relayerId, uint256 lockUntilBlock)
public
payable
{
uint256 targetEpoch = getCurrentEpoch();
uint256 index = epochRelayerIndex[targetEpoch][relayerId];
//Check that Relayer is in list
require(index > 0, "Relayer not found");
//Check that Relayer has remaiining funds(Is active), Deposit amount grater than zero, lock until Block is greater than current Block
require(
relayers[targetEpoch][index].remainingPenaltyFunds > 0,
"Relayer doesn't have any remaining penalty funds"
);
require(msg.value > 0, "Deposit amount should be greater then 0");
require(
lockUntilBlock > block.number,
"The lockTimeInDays should be greater than zero"
);
//If 1st deposit on Relayer increase the numner of Relayer current users
if (userDepositOnRelayer[msg.sender][relayerId].lockUntilBlock == 0) {
relayers[targetEpoch][index].currentUsers += 1;
} else {
//Check that new lock until value is greater or equal than existing
require(
userDepositOnRelayer[msg.sender][relayerId].lockUntilBlock <=
lockUntilBlock,
"The lockTimeInDays should be greater than any previous lock until Block"
);
}
userDepositOnRelayer[msg.sender][relayerId]
.lockUntilBlock = lockUntilBlock;
//Check if current Relayer users exceeds the Relayer license
require(
relayers[targetEpoch][index].currentUsers <=
relayers[targetEpoch][index].maxUsers,
"Max users limit violated"
);
//Add coins to total Relayer Deposits
relayers[targetEpoch][index].currentCoins += msg.value;
//Check if total Relayer Deposits exceeds tha Relayer license
require(
relayers[targetEpoch][index].currentCoins <=
relayers[targetEpoch][index].maxCoins,
"Max coins limit violated"
);
//Add Tx amount to User balance
userDepositOnRelayer[msg.sender][relayerId].balance += msg.value;
//Notify for Deposit
emit UserDeposit(relayerId, msg.sender, msg.value);
}
//User withdraw funds from Relayer
function withdrawFunds(address relayerId, uint256 amount) public {
//Check if balance is still locked
require(
userDepositOnRelayer[msg.sender][relayerId].lockUntilBlock <
block.number,
"Balance locked"
);
//Check if balance is greater than requested amount
require(
userDepositOnRelayer[msg.sender][relayerId].balance >= amount,
"Insufficient balance"
);
//Remove requested amount from User balance
userDepositOnRelayer[msg.sender][relayerId].balance -= amount;
//Transfer money to User address
msg.sender.transfer(amount);
//Notifu for Withdrawal
emit UserWithdraw(relayerId, msg.sender, amount);
}
//Return the User as Signer of Offchain Tx checking that input parameters are valid
// h is the hash of signature
// r and s are outputs of the ECDSA signature
// v is the recovery id
// nonce is The P2P Tx unique identifier
// fee is the Relayer fee
// beneficiary is the Beneficiary address
// amount is the amount to be transfered
function checkOffchainSignature(
bytes32 h,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 nonce,
uint256 fee,
address payable beneficiary,
uint256 amount
) public pure returns (address signer) {
//Calculate hash of input arguments beneficiary, nonce and amount
bytes32 proof = keccak256(
abi.encodePacked(beneficiary, nonce, amount, fee)
);
//The hash of input arguments should be equal with provided Offcain transaction Hash(Parameter h)
require(
proof == h,
"Off-chain transaction hash does't match with payload"
);
//Recover the Offcain transaction Signer using ECDA public key Recovery(User that signed the Tx)
signer = ecrecover(h, v, r, s);
return signer;
}
//Return the Relayer as Signer of Offchain Tx checking that input parameters are valid
// proof is the Hash of User generated Offchain Payment
// rh is the hash of signature
// rr and rs are outputs of the ECDSA signature
// rv is the recovery id
// txUntilBlock is the Block number that Relayer should proceed with the Tx Onchain. Otherwise should be penaltized with the amount reducing Relayer ramining funds
function checkOffchainRelayerSignature(
bytes32 proof,
bytes32 rh,
uint8 rv,
bytes32 rr,
bytes32 rs,
uint256 txUntilBlock
) public pure returns (address payable relayerid) {
//Calculate hash of input arguments txUntilBlock and proof
bytes32 relayerProof = keccak256(abi.encodePacked(proof, txUntilBlock));
//The hash of input arguments should be equal with provided Offcain transaction Hash(Parameter rh)
require(
relayerProof == rh,
"Off-chain transaction hash does't match with payload"
);
//Recover the Offcain transaction Signer using ECDA public key Recovery(Relayer that signed the Tx)
address relayer = ecrecover(rh, rv, rr, rs);
relayerid = address(uint160((relayer)));
return relayerid;
}
//Calculate the fund required to be locked by a Relayer when requesting a new license
//maxUsers is the requested max number of Peers(Depositors)
//maxCoins is the requested max Coins could be deposited by Peers(Total Deposits)
//maxTxThroughputPer100000Blocks is the requested max allowed Offcain transactions throughput per 100000 Blocks
function getFundRequiredForRelayer(
uint256 maxUsers,
uint256 maxCoins,
uint256 maxTxThroughputPer100000Blocks
) public pure returns (uint256 requiredAmount) {
if (maxUsers <= 1000) {
requiredAmount += maxUsers.mul(100 * 1 ether);
} else {
requiredAmount += 1000 * 100 * 1 ether;
maxUsers -= 1000;
if (maxUsers <= 10000) {
requiredAmount += maxUsers.mul(50 * 1 ether);
} else {
requiredAmount += 10000 * 50 * 1 ether;
maxUsers -= 10000;
if (maxUsers <= 100000) {
requiredAmount += maxUsers.mul(25 * 1 ether);
} else {
requiredAmount += 100000 * 25 * 1 ether;
maxUsers -= 100000;
if (maxUsers <= 1000000) {
requiredAmount += maxUsers.mulByFraction(
125 * 1 ether,
10
);
} else {
requiredAmount += 1000000 * (125 / 10) * 1 ether;
maxUsers -= 1000000;
requiredAmount += maxUsers.mul(10 * 1 ether);
}
}
}
}
if (maxCoins <= 1000 * 1 ether) {
requiredAmount += maxCoins.mulByFraction(500, 1000);
} else {
requiredAmount += (1000 * 500) / 1000;
maxCoins -= 1000 * 1 ether;
if (maxCoins <= 10000 * 1 ether) {
requiredAmount += maxCoins.mulByFraction(200, 1000);
} else {
requiredAmount += (10000 * 200) / 1000;
maxCoins -= 10000 * 1 ether;
if (maxCoins <= 100000 * 1 ether) {
requiredAmount += maxCoins.mulByFraction(100, 1000);
} else {
requiredAmount += (100000 * 100) / 1000;
maxCoins -= 100000 * 1 ether;
if (maxCoins <= 1000000 * 1 ether) {
requiredAmount += maxCoins.mulByFraction(10, 1000);
} else {
requiredAmount += (1000000 * 10) / 1000;
maxCoins -= 1000000 * 1 ether;
requiredAmount += maxCoins.mulByFraction(1, 1000);
}
}
}
}
if (maxTxThroughputPer100000Blocks <= 10) {
requiredAmount += maxTxThroughputPer100000Blocks.mulByFraction(
10000 * 1 ether,
100000
);
} else {
requiredAmount += (10 * 10000 * 1 ether) / 100000;
maxTxThroughputPer100000Blocks -= 10;
if (maxTxThroughputPer100000Blocks <= 1000) {
requiredAmount += maxTxThroughputPer100000Blocks.mulByFraction(
120000 * 1 ether,
100000
);
} else {
requiredAmount += (1000 * 120000 * 1 ether) / 100000;
maxTxThroughputPer100000Blocks -= 1000;
if (maxTxThroughputPer100000Blocks <= 100000) {
requiredAmount += maxTxThroughputPer100000Blocks
.mulByFraction(150000 * 1 ether, 100000);
} else {
requiredAmount += (100000 * 150000 * 1 ether) / 100000;
maxTxThroughputPer100000Blocks -= 100000;
if (maxTxThroughputPer100000Blocks <= 10000000) {
requiredAmount += maxTxThroughputPer100000Blocks
.mulByFraction(200000 * 1 ether, 100000);
} else {
requiredAmount +=
(10000000 * 200000 * 1 ether) /
100000;
maxTxThroughputPer100000Blocks -= 10000000;
requiredAmount += maxTxThroughputPer100000Blocks
.mulByFraction(1000000 * 1 ether, 100000);
}
}
}
}
}
//Settle a P2P Offchain Transaction through a Relayer that has signed the Tx
// h is the hash of P2P signature
// r and s are outputs of the ECDSA P2P signature
// v is the recovery id of P2P signature
// rh is the hash of Relayer signature
// rr and rs are outputs of the ECDSA Relayer signature
// rv is the recovery id of Relayer signature
// nonce is The P2P Tx unique identifier
// fee is the Relayer fee
// txUntilBlock is the Block number that Relayer should proceed with the Tx Onchain
// the Beneficiary address
// The amount to be tranfered from locked initiator(P2P Tx Siginer) amount to beneficiary
function finalizeOffchainRelayerTransaction(
bytes32 h,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 rh,
uint8 rv,
bytes32 rr,
bytes32 rs,
bytes32 nonce,
uint256 fee,
uint256 txUntilBlock,
address payable beneficiary,
uint256 amount
) public {
//Check and get P2P Signer
address signer = checkOffchainSignature(
h,
v,
r,
s,
nonce,
fee,
beneficiary,
amount
);
//Check and get Relayer
address payable relayerId = checkOffchainRelayerSignature(
h,
rh,
rv,
rr,
rs,
txUntilBlock
);
//Get the Epoch of the txUntilBlock
uint256 epoch = getEpochByBlock(txUntilBlock);
//Get the Relayer of above Epoch
uint256 index = epochRelayerIndex[epoch][relayerId];
//If Relayer not found and not the Initial Epoch try get the Relayer of the previous Epoch
if (index == 0 && epoch > 1) {
epoch = epoch - 1;
index = epochRelayerIndex[epoch][relayerId];
}
//Check that Relayer finally found
require(index > 0, "Relayer not found");
//Check the requested amount is greater than the previously used of the same nonce
require(
userToBeneficiaryFinalizedAmountForNonce[signer][beneficiary][relayerId][nonce] <
amount,
"Requested amount should be greater than the previous finalized for withdraw request or P2P content transaction"
);
//Get the delta between requested and the previously used of the same nonce
uint256 amountToBeTransferred = amount -
userToBeneficiaryFinalizedAmountForNonce[signer][beneficiary][relayerId][nonce];
//Set amount as the last used of the same nonce
userToBeneficiaryFinalizedAmountForNonce[signer][beneficiary][relayerId][nonce] = amount;
uint256 relayerFee = 0;
bool isPayedFromPenaltyFunds = false;
//Find if the P2P user or Relayer should pay in case of delayed Tx
if (txUntilBlock >= block.number) {
//Check that P2P Signer has the required balance on Relayer
require(
userDepositOnRelayer[signer][relayerId].balance >=
amountToBeTransferred,
"Insufficient balance"
);
userDepositOnRelayer[signer][relayerId]
.balance -= amountToBeTransferred;
relayerFee = amountToBeTransferred.mulByFraction(fee, 1000);
} else {
isPayedFromPenaltyFunds = true;
relayers[epoch][index]
.remainingPenaltyFunds -= amountToBeTransferred;
}
//Transfer the money to Beneficiary address
beneficiary.transfer(amountToBeTransferred - relayerFee);
//If there is a fee transfer to Relayer Owner address
if (relayerFee > 0) {
relayerId.transfer(relayerFee);
}
//Notity for Settlement
emit RelayedOffChainTransaction(
relayerId,
signer,
beneficiary,
relayerFee,
amountToBeTransferred,
isPayedFromPenaltyFunds
);
}
}
| User withdraw funds from RelayerCheck if balance is still lockedCheck if balance is greater than requested amountRemove requested amount from User balanceTransfer money to User addressNotifu for Withdrawal | function withdrawFunds(address relayerId, uint256 amount) public {
require(
userDepositOnRelayer[msg.sender][relayerId].lockUntilBlock <
block.number,
"Balance locked"
);
require(
userDepositOnRelayer[msg.sender][relayerId].balance >= amount,
"Insufficient balance"
);
userDepositOnRelayer[msg.sender][relayerId].balance -= amount;
msg.sender.transfer(amount);
emit UserWithdraw(relayerId, msg.sender, amount);
}
| 15,860,511 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol";
import "../interface/IOracle.sol";
import "../libraries/OrderData.sol";
import "../libraries/SafeMathExt.sol";
import "../libraries/Utils.sol";
import "./AMMModule.sol";
import "./LiquidityPoolModule.sol";
import "./MarginAccountModule.sol";
import "./PerpetualModule.sol";
import "../Type.sol";
library TradeModule {
using SafeMathExt for int256;
using SignedSafeMathUpgradeable for int256;
using OrderData for uint32;
using AMMModule for LiquidityPoolStorage;
using LiquidityPoolModule for LiquidityPoolStorage;
using MarginAccountModule for PerpetualStorage;
using PerpetualModule for PerpetualStorage;
using MarginAccountModule for MarginAccount;
event Trade(
uint256 perpetualIndex,
address indexed trader,
int256 position,
int256 price,
int256 fee,
int256 lpFee
);
event Liquidate(
uint256 perpetualIndex,
address indexed liquidator,
address indexed trader,
int256 amount,
int256 price,
int256 penalty,
int256 penaltyToLP
);
event TransferFeeToOperator(address indexed operator, int256 operatorFee);
event TransferFeeToReferrer(
uint256 perpetualIndex,
address indexed trader,
address indexed referrer,
int256 referralRebate
);
/**
* @dev See `trade` in Perpetual.sol for details.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param trader The address of trader.
* @param amount The amount of position to trader, positive for buying and negative for selling.
* @param limitPrice The worst price the trader accepts.
* @param referrer The address of referrer who will get rebate in the deal.
* @param flags The flags of the trade, contains extra config for trading.
* @return tradeAmount The amount of positions actually traded in the transaction.
*/
function trade(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
int256 amount,
int256 limitPrice,
address referrer,
uint32 flags
) public returns (int256 tradeAmount) {
(int256 deltaCash, int256 deltaPosition) = preTrade(
liquidityPool,
perpetualIndex,
trader,
amount,
limitPrice,
flags
);
doTrade(liquidityPool, perpetualIndex, trader, deltaCash, deltaPosition);
(int256 lpFee, int256 totalFee) = postTrade(
liquidityPool,
perpetualIndex,
trader,
referrer,
deltaCash,
deltaPosition,
flags
);
emit Trade(
perpetualIndex,
trader,
deltaPosition.neg(),
deltaCash.wdiv(deltaPosition).abs(),
totalFee,
lpFee
);
tradeAmount = deltaPosition.neg();
require(
liquidityPool.isTraderMarginSafe(perpetualIndex, trader, tradeAmount),
"trader margin unsafe"
);
}
function preTrade(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
int256 amount,
int256 limitPrice,
uint32 flags
) internal returns (int256 deltaCash, int256 deltaPosition) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
require(!IOracle(perpetual.oracle).isMarketClosed(), "market is closed now");
// handle close only flag
if (flags.isCloseOnly()) {
amount = getMaxPositionToClose(perpetual.getPosition(trader), amount);
require(amount != 0, "no amount to close");
}
// query price from AMM
(deltaCash, deltaPosition) = liquidityPool.queryTradeWithAMM(
perpetualIndex,
amount.neg(),
false
);
// check price
if (!flags.isMarketOrder()) {
int256 tradePrice = deltaCash.wdiv(deltaPosition).abs();
validatePrice(amount >= 0, tradePrice, limitPrice);
}
}
function doTrade(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
int256 deltaCash,
int256 deltaPosition
) internal {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
int256 deltaOpenInterest1 = perpetual.updateMargin(address(this), deltaPosition, deltaCash);
int256 deltaOpenInterest2 = perpetual.updateMargin(
trader,
deltaPosition.neg(),
deltaCash.neg()
);
require(perpetual.openInterest >= 0, "negative open interest");
if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) {
// open interest will increase, check limit
(int256 poolMargin, ) = liquidityPool.getPoolMargin();
require(
perpetual.openInterest <=
perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()),
"open interest exceeds limit"
);
}
}
/**
* @dev Execute the trade. If the trader has opened position in the trade, his account should be
* initial margin safe after the trade. If not, his account should be margin safe
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of pereptual storage.
* @param trader The address of trader.
* @param referrer The address of referrer who will get rebate from the deal.
* @param deltaCash The amount of cash changes in a trade.
* @param deltaPosition The amount of position changes in a trade.
* @return lpFee The amount of fee for lp provider.
* @return totalFee The total fee collected from the trader after the trade.
*/
function postTrade(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
address referrer,
int256 deltaCash,
int256 deltaPosition,
uint32 flags
) internal returns (int256 lpFee, int256 totalFee) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
// fees
int256 operatorFee;
int256 vaultFee;
int256 referralRebate;
{
bool hasOpened = Utils.hasOpenedPosition(
perpetual.getPosition(trader),
deltaPosition.neg()
);
(lpFee, operatorFee, vaultFee, referralRebate) = getFees(
liquidityPool,
perpetual,
trader,
referrer,
deltaCash.abs(),
hasOpened
);
}
totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate);
perpetual.updateCash(trader, totalFee.neg());
// trader deposit/withdraw
if (flags.useTargetLeverage()) {
liquidityPool.adjustMarginLeverage(
perpetualIndex,
trader,
deltaPosition.neg(),
deltaCash.neg(),
totalFee
);
}
// send fee
transferFee(
liquidityPool,
perpetualIndex,
trader,
referrer,
lpFee,
operatorFee,
vaultFee,
referralRebate
);
}
/**
* @dev Get the fees of the trade. If the margin of the trader is not enough for fee:
* 1. If trader open position, the trade will be reverted.
* 2. If trader close position, the fee will be decreasing in proportion according to
* the margin left in the trader's account
* The rebate of referral will only calculate the lpFee and operatorFee.
* The vault fee will not be counted in.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetual The reference of pereptual storage.
* @param trader The address of trader.
* @param referrer The address of referrer who will get rebate from the deal.
* @param tradeValue The amount of trading value, measured by collateral, abs of deltaCash.
* @return lpFee The amount of fee to the Liquidity provider.
* @return operatorFee The amount of fee to the operator.
* @return vaultFee The amount of fee to the vault.
* @return referralRebate The amount of rebate of the refferral.
*/
function getFees(
LiquidityPoolStorage storage liquidityPool,
PerpetualStorage storage perpetual,
address trader,
address referrer,
int256 tradeValue,
bool hasOpened
)
public
view
returns (
int256 lpFee,
int256 operatorFee,
int256 vaultFee,
int256 referralRebate
)
{
require(tradeValue >= 0, "trade value is negative");
vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate());
lpFee = tradeValue.wmul(perpetual.lpFeeRate);
if (liquidityPool.getOperator() != address(0)) {
operatorFee = tradeValue.wmul(perpetual.operatorFeeRate);
}
int256 totalFee = lpFee.add(operatorFee).add(vaultFee);
int256 availableMargin = perpetual.getAvailableMargin(trader, perpetual.getMarkPrice());
if (!hasOpened) {
if (availableMargin <= 0) {
lpFee = 0;
operatorFee = 0;
vaultFee = 0;
referralRebate = 0;
} else if (totalFee > availableMargin) {
// make sure the sum of fees < available margin
int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR);
operatorFee = operatorFee.wmul(rate, Round.FLOOR);
vaultFee = vaultFee.wmul(rate, Round.FLOOR);
lpFee = availableMargin.sub(operatorFee).sub(vaultFee);
}
}
if (
referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0
) {
int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate);
int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate);
referralRebate = lpFeeRebate.add(operatorFeeRabate);
lpFee = lpFee.sub(lpFeeRebate);
operatorFee = operatorFee.sub(operatorFeeRabate);
}
}
function transferFee(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
address referrer,
int256 lpFee,
int256 operatorFee,
int256 vaultFee,
int256 referralRebate
) internal {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
perpetual.updateCash(address(this), lpFee);
liquidityPool.transferFromPerpetualToUser(perpetual.id, referrer, referralRebate);
liquidityPool.transferFromPerpetualToUser(perpetual.id, liquidityPool.getVault(), vaultFee);
address operator = liquidityPool.getOperator();
liquidityPool.transferFromPerpetualToUser(perpetual.id, operator, operatorFee);
emit TransferFeeToOperator(operator, operatorFee);
emit TransferFeeToReferrer(perpetual.id, trader, referrer, referralRebate);
}
/**
* @dev See `liquidateByAMM` in Perpetual.sol for details.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param liquidator The address of the account calling the liquidation method.
* @param trader The address of the liquidated account.
* @return liquidatedAmount The amount of positions actually liquidated in the transaction.
*/
function liquidateByAMM(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address liquidator,
address trader
) public returns (int256 liquidatedAmount) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
require(
!perpetual.isMaintenanceMarginSafe(trader, perpetual.getMarkPrice()),
"trader is safe"
);
int256 position = perpetual.getPosition(trader);
// 0. price / amount
(int256 deltaCash, int256 deltaPosition) = liquidityPool.queryTradeWithAMM(
perpetualIndex,
position,
true
);
require(deltaPosition != 0, "insufficient liquidity");
// 2. trade
int256 liquidatePrice = deltaCash.wdiv(deltaPosition).abs();
perpetual.updateMargin(address(this), deltaPosition, deltaCash);
perpetual.updateMargin(
trader,
deltaPosition.neg(),
deltaCash.add(perpetual.keeperGasReward).neg()
);
require(perpetual.openInterest >= 0, "negative open interest");
liquidityPool.transferFromPerpetualToUser(
perpetual.id,
liquidator,
perpetual.keeperGasReward
);
// 3. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition
(int256 penalty, int256 penaltyToLiquidator) = postLiquidate(
liquidityPool,
perpetual,
address(this),
trader,
position,
deltaPosition.neg()
);
emit Liquidate(
perpetualIndex,
address(this),
trader,
deltaPosition.neg(),
liquidatePrice,
penalty,
penaltyToLiquidator
);
liquidatedAmount = deltaPosition.neg();
}
/**
* @dev See `liquidateByTrader` in Perpetual.sol for details.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param liquidator The address of the account calling the liquidation method.
* @param trader The address of the liquidated account.
* @param amount The amount of position to be taken from liquidated trader.
* @param limitPrice The worst price liquidator accepts.
* @return liquidatedAmount The amount of positions actually liquidated in the transaction.
*/
function liquidateByTrader(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address liquidator,
address trader,
int256 amount,
int256 limitPrice
) public returns (int256 liquidatedAmount) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
int256 markPrice = perpetual.getMarkPrice();
require(!perpetual.isMaintenanceMarginSafe(trader, markPrice), "trader is safe");
// 0. price / amount
validatePrice(amount >= 0, markPrice, limitPrice);
int256 position = perpetual.getPosition(trader);
int256 deltaPosition = getMaxPositionToClose(position, amount.neg()).neg();
int256 deltaCash = markPrice.wmul(deltaPosition).neg();
// 1. execute
perpetual.updateMargin(liquidator, deltaPosition, deltaCash);
perpetual.updateMargin(trader, deltaPosition.neg(), deltaCash.neg());
require(perpetual.openInterest >= 0, "negative open interest");
// 2. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition
(int256 penalty, ) = postLiquidate(
liquidityPool,
perpetual,
liquidator,
trader,
position,
deltaPosition.neg()
);
liquidatedAmount = deltaPosition.neg();
require(
liquidityPool.isTraderMarginSafe(perpetualIndex, liquidator, liquidatedAmount),
"liquidator margin unsafe"
);
emit Liquidate(perpetualIndex, liquidator, trader, liquidatedAmount, markPrice, penalty, 0);
}
/**
* @dev Handle liquidate penalty / fee.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetual The reference of perpetual storage.
* @param liquidator The address of the account calling the liquidation method.
* @param trader The address of the liquidated account.
* @param position The amount of position owned by trader before liquidation.
* @param deltaPosition The amount of position to be taken from liquidated trader.
* @return penalty The amount of positions actually liquidated in the transaction.
* @return penaltyToLiquidator The amount of positions actually liquidated in the transaction.
*/
function postLiquidate(
LiquidityPoolStorage storage liquidityPool,
PerpetualStorage storage perpetual,
address liquidator,
address trader,
int256 position,
int256 deltaPosition
) public returns (int256 penalty, int256 penaltyToLiquidator) {
int256 vaultFee = 0;
{
int256 markPrice = perpetual.getMarkPrice();
int256 remainingMargin = perpetual.getMargin(trader, markPrice);
int256 liquidationValue = markPrice.wmul(deltaPosition).abs();
penalty = liquidationValue.wmul(perpetual.liquidationPenaltyRate).min(
remainingMargin.wfrac(deltaPosition.abs(), position.abs())
);
remainingMargin = remainingMargin.sub(penalty);
if (remainingMargin > 0) {
vaultFee = liquidationValue.wmul(liquidityPool.getVaultFeeRate()).min(
remainingMargin
);
liquidityPool.transferFromPerpetualToUser(
perpetual.id,
liquidityPool.getVault(),
vaultFee
);
}
}
int256 penaltyToFund;
bool isEmergency;
if (penalty > 0) {
penaltyToFund = penalty.wmul(perpetual.insuranceFundRate);
penaltyToLiquidator = penalty.sub(penaltyToFund);
} else {
int256 totalInsuranceFund = liquidityPool.insuranceFund.add(
liquidityPool.donatedInsuranceFund
);
if (totalInsuranceFund.add(penalty) < 0) {
// ensure donatedInsuranceFund >= 0
penalty = totalInsuranceFund.neg();
isEmergency = true;
}
penaltyToFund = penalty;
penaltyToLiquidator = 0;
}
int256 penaltyToLP = liquidityPool.updateInsuranceFund(penaltyToFund);
perpetual.updateCash(address(this), penaltyToLP);
perpetual.updateCash(liquidator, penaltyToLiquidator);
perpetual.updateCash(trader, penalty.add(vaultFee).neg());
if (penaltyToFund >= 0) {
perpetual.decreaseTotalCollateral(penaltyToFund.sub(penaltyToLP));
} else {
// penaltyToLP = 0 when penaltyToFund < 0
perpetual.increaseTotalCollateral(penaltyToFund.neg());
}
if (isEmergency) {
liquidityPool.setEmergencyState(perpetual.id);
}
}
/**
* @dev Get the max position amount of trader will be closed in the trade.
* @param position Current position of trader.
* @param amount The trading amount of position.
* @return maxPositionToClose The max position amount of trader will be closed in the trade.
*/
function getMaxPositionToClose(int256 position, int256 amount)
internal
pure
returns (int256 maxPositionToClose)
{
require(position != 0, "trader has no position to close");
require(!Utils.hasTheSameSign(position, amount), "trader must be close only");
maxPositionToClose = amount.abs() > position.abs() ? position.neg() : amount;
}
/**
* @dev Check if the price is better than the limit price.
* @param isLong True if the side is long.
* @param price The price to be validate.
* @param priceLimit The limit price.
*/
function validatePrice(
bool isLong,
int256 price,
int256 priceLimit
) internal pure {
require(price > 0, "price must be positive");
bool isPriceSatisfied = isLong ? price <= priceLimit : price >= priceLimit;
require(isPriceSatisfied, "price exceeds limit");
}
/**
* @dev A readonly version of trade
*
* This function was written post-audit. So there's a lot of repeated logic here.
* NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin
* will be smaller, so that the openInterst limit is also smaller (more strict).
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param trader The address of trader.
* @param amount The amount of position to trader, positive for buying and negative for selling.
* @param flags The flags of the trade, contains extra config for trading.
* @return tradePrice The average fill price.
* @return totalFee The total fee collected from the trader after the trade.
* @return cost Deposit or withdraw to let effective leverage == targetLeverage if flags contain USE_TARGET_LEVERAGE. > 0 if deposit, < 0 if withdraw.
*/
function queryTrade(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
address trader,
int256 amount,
address referrer,
uint32 flags
)
public
returns (
int256 tradePrice,
int256 totalFee,
int256 cost
)
{
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
MarginAccount memory account = perpetual.marginAccounts[trader]; // clone
(int256 deltaCash, int256 deltaPosition) = preTrade(
liquidityPool,
perpetualIndex,
trader,
amount,
amount > 0 ? type(int256).max : 0,
flags
);
tradePrice = deltaCash.wdiv(deltaPosition).abs();
readonlyDoTrade(liquidityPool, perpetual, account, deltaCash, deltaPosition);
(totalFee, cost) = readonlyPostTrade(
liquidityPool,
perpetual,
account,
referrer,
deltaCash,
deltaPosition,
flags
);
}
// A readonly version of doTrade. This function was written post-audit. So there's a lot of repeated logic here.
// NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin
// will be smaller, so that the openInterst limit is also smaller (more strict).
function readonlyDoTrade(
LiquidityPoolStorage storage liquidityPool,
PerpetualStorage storage perpetual,
MarginAccount memory account,
int256 deltaCash,
int256 deltaPosition
) internal view {
int256 deltaOpenInterest1;
int256 deltaOpenInterest2;
(, , deltaOpenInterest1) = readonlyUpdateMargin(
perpetual,
perpetual.marginAccounts[address(this)].cash,
perpetual.marginAccounts[address(this)].position,
deltaPosition,
deltaCash
);
(account.cash, account.position, deltaOpenInterest2) = readonlyUpdateMargin(
perpetual,
account.cash,
account.position,
deltaPosition.neg(),
deltaCash.neg()
);
int256 perpetualOpenInterest = perpetual.openInterest.add(deltaOpenInterest1).add(
deltaOpenInterest2
);
require(perpetualOpenInterest >= 0, "negative open interest");
if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) {
// open interest will increase, check limit
(int256 poolMargin, ) = liquidityPool.getPoolMargin(); // NOTE: this is a slight different from trade()
require(
perpetualOpenInterest <=
perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()),
"open interest exceeds limit"
);
}
}
// A readonly version of postTrade. This function was written post-audit. So there's a lot of repeated logic here.
function readonlyPostTrade(
LiquidityPoolStorage storage liquidityPool,
PerpetualStorage storage perpetual,
MarginAccount memory account,
address referrer,
int256 deltaCash,
int256 deltaPosition,
uint32 flags
) internal view returns (int256 totalFee, int256 adjustCollateral) {
// fees
int256 lpFee;
int256 operatorFee;
int256 vaultFee;
int256 referralRebate;
{
bool hasOpened = Utils.hasOpenedPosition(account.position, deltaPosition.neg());
(lpFee, operatorFee, vaultFee, referralRebate) = readonlyGetFees(
liquidityPool,
perpetual,
account,
referrer,
deltaCash.abs(),
hasOpened
);
}
totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate);
// was updateCash
account.cash = account.cash.add(totalFee.neg());
// trader deposit/withdraw
if (flags.useTargetLeverage()) {
adjustCollateral = LiquidityPoolModule.readonlyAdjustMarginLeverage(
perpetual,
account,
deltaPosition.neg(),
deltaCash.neg(),
totalFee
);
}
account.cash = account.cash.add(adjustCollateral);
}
// A readonly version of MarginAccountModule.updateMargin. This function was written post-audit. So there's a lot of repeated logic here.
function readonlyUpdateMargin(
PerpetualStorage storage perpetual,
int256 oldCash,
int256 oldPosition,
int256 deltaPosition,
int256 deltaCash
)
internal
view
returns (
int256 newCash,
int256 newPosition,
int256 deltaOpenInterest
)
{
newPosition = oldPosition.add(deltaPosition);
newCash = oldCash.add(deltaCash).add(perpetual.unitAccumulativeFunding.wmul(deltaPosition));
if (oldPosition > 0) {
deltaOpenInterest = oldPosition.neg();
}
if (newPosition > 0) {
deltaOpenInterest = deltaOpenInterest.add(newPosition);
}
}
// A readonly version of getFees. This function was written post-audit. So there's a lot of repeated logic here.
function readonlyGetFees(
LiquidityPoolStorage storage liquidityPool,
PerpetualStorage storage perpetual,
MarginAccount memory trader,
address referrer,
int256 tradeValue,
bool hasOpened
)
public
view
returns (
int256 lpFee,
int256 operatorFee,
int256 vaultFee,
int256 referralRebate
)
{
require(tradeValue >= 0, "trade value is negative");
vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate());
lpFee = tradeValue.wmul(perpetual.lpFeeRate);
if (liquidityPool.getOperator() != address(0)) {
operatorFee = tradeValue.wmul(perpetual.operatorFeeRate);
}
int256 totalFee = lpFee.add(operatorFee).add(vaultFee);
int256 availableMargin = LiquidityPoolModule.readonlyGetAvailableMargin(
perpetual,
trader,
perpetual.getMarkPrice()
);
if (!hasOpened) {
if (availableMargin <= 0) {
lpFee = 0;
operatorFee = 0;
vaultFee = 0;
referralRebate = 0;
} else if (totalFee > availableMargin) {
// make sure the sum of fees < available margin
int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR);
operatorFee = operatorFee.wmul(rate, Round.FLOOR);
vaultFee = vaultFee.wmul(rate, Round.FLOOR);
lpFee = availableMargin.sub(operatorFee).sub(vaultFee);
}
}
if (
referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0
) {
int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate);
int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate);
referralRebate = lpFeeRebate.add(operatorFeeRabate);
lpFee = lpFee.sub(lpFeeRebate);
operatorFee = operatorFee.sub(operatorFeeRabate);
}
}
}
| A readonly version of MarginAccountModule.updateMargin. This function was written post-audit. So there's a lot of repeated logic here. | function readonlyUpdateMargin(
PerpetualStorage storage perpetual,
int256 oldCash,
int256 oldPosition,
int256 deltaPosition,
int256 deltaCash
)
internal
view
returns (
int256 newCash,
int256 newPosition,
int256 deltaOpenInterest
)
{
newPosition = oldPosition.add(deltaPosition);
newCash = oldCash.add(deltaCash).add(perpetual.unitAccumulativeFunding.wmul(deltaPosition));
if (oldPosition > 0) {
deltaOpenInterest = oldPosition.neg();
}
if (newPosition > 0) {
deltaOpenInterest = deltaOpenInterest.add(newPosition);
}
}
| 12,615,802 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
contract HireyStore {
struct CVRecord {
address author;
string documentHash;
}
struct CVDocument {
address author;
string documentHash;
bool isUnlocked;
address[] sharedTo;
}
address payable private contractCreatorAddress;
mapping(address => CVRecord[]) private cvRecordHashes;
mapping(address => CVDocument[]) private cvDocumentHashes;
constructor() public {
contractCreatorAddress = msg.sender;
}
// Eine Bildungsinstitution oder ein Arbeitgeber kann einen _cvRecordHash für einen Bewerber hinzufügen. Dieser _cvRecordHash zeigt auf eine Datei (auf dem IPFS),
// welche vom Sender signiert und mit dem Public-Key des Bewerbers verschlüsselt wurde. Der Hash wurde mit dem HIREY-System Public-Key verschlüsselt.
function storeCvRecordFor(address _applicantAccount, string memory _cvRecordHash) public {
cvRecordHashes[_applicantAccount].push(CVRecord({author: msg.sender, documentHash: _cvRecordHash}));
}
// Ein Bewerber kann einen _cvDocumentHash für sich selbst speichern. Die Datei auf IPFS enthält mehere cvRecords.
// Die cvRecords wurden vom ursprünglichen Sender signiert. Gespeichert ist das cvDocument hier ebenfalls mit dem Public-Key des Bewerbers.
// Der Hash wurde mit dem HIREY-System Public-Key verschlüsselt.
function storeCVDocument(string memory _cvDocumentHash) public {
cvDocumentHashes[msg.sender].push(CVDocument({author: msg.sender, documentHash: _cvDocumentHash, isUnlocked: true, sharedTo: new address[](0)}));
}
// Bewerber kann seine CVDocumente für HR-Abteilungen freigeben. Die HR-Abteilung muss den Eintrag dann mit Eth freischalten (unlock=True).
// Beim Teilen gibt er den _cvDocumentHash des freizugebenden CVDocumentes mit. Dieses Dokument enthält die von den Firmen und Schulen signierten
// cvRecords. Die cvRecords und das gesamte Dokument wurde mit dem Public-Key der HR-Abteilung verschlüsselt. Der Hash wurde mit dem HIREY-System Public-Key verschlüsselt.
function shareCVDocument(address _targetAccount, uint cvDocumentIndex, string memory _cvDocumentHash) public {
require(_targetAccount != msg.sender); // Um ein Dokument für dich selber zu speichern muss mann storeCVDocument verwenden
// das Dokument dass man freigibt muss auch existieren
require(cvDocumentHashes[msg.sender].length > cvDocumentIndex);
require(bytes(cvDocumentHashes[msg.sender][cvDocumentIndex].documentHash).length > 0);
cvDocumentHashes[_targetAccount].push(CVDocument({author: msg.sender, documentHash: _cvDocumentHash, isUnlocked: false, sharedTo: new address[](0)}));
cvDocumentHashes[msg.sender][cvDocumentIndex].sharedTo.push(_targetAccount);
}
// Die HR-Abteilungen bezahlen für das Anschauen der CVDokumente einmalig. Daher müssen sie das Dokument initial freischalten.
// Nur freigeschaltete CVDocument-Hashes werden durch den HIREY-SYSTEM Private-Key entschlüsselt.
function unlockCVDocument(uint cvDocumentIndex) public payable {
require(!cvDocumentHashes[msg.sender][cvDocumentIndex].isUnlocked);
require(msg.value >= 30000);
contractCreatorAddress.transfer(msg.value);
cvDocumentHashes[msg.sender][cvDocumentIndex].isUnlocked = true;
}
function getNbrOfCvRecordHashes() public view returns (uint) {
return cvRecordHashes[msg.sender].length;
}
function getCvRecordHash(uint cvRecordIndex) public view returns (address, string memory) {
return (cvRecordHashes[msg.sender][cvRecordIndex].author, cvRecordHashes[msg.sender][cvRecordIndex].documentHash);
}
function getNbrOfCvDocumentHashes() public view returns (uint count) {
return cvDocumentHashes[msg.sender].length;
}
// Der CVDocumentHash kann immer Abgefragt werden. Dieser wird einfach nicht vom System entschlüsselt, wenn er nicht freigeschaltet ist.
function getCvDocumentHash(uint cvDocumentIndex) public view returns (address, string memory) {
return (cvDocumentHashes[msg.sender][cvDocumentIndex].author, cvDocumentHashes[msg.sender][cvDocumentIndex].documentHash);
}
function isCvDocumentUnlocked(uint cvDocumentIndex) public view returns (bool) {
return cvDocumentHashes[msg.sender][cvDocumentIndex].isUnlocked;
}
function getNbrOfSharedTo(uint cvDocumentIndex) public view returns (uint) {
return cvDocumentHashes[msg.sender][cvDocumentIndex].sharedTo.length;
}
function getSharedTo(uint cvDocumentIndex, uint sharedToIndex) public view returns (address) {
return cvDocumentHashes[msg.sender][cvDocumentIndex].sharedTo[sharedToIndex];
}
} | Ein Bewerber kann einen _cvDocumentHash für sich selbst speichern. Die Datei auf IPFS enthält mehere cvRecords. Die cvRecords wurden vom ursprünglichen Sender signiert. Gespeichert ist das cvDocument hier ebenfalls mit dem Public-Key des Bewerbers. Der Hash wurde mit dem HIREY-System Public-Key verschlüsselt. | function storeCVDocument(string memory _cvDocumentHash) public {
}
| 2,558,922 |
pragma solidity ^0.5.0;
import "./Project.sol";
import "./ProjectLibrary.sol";
import "./ProjectRegistry.sol";
import "./HyphaToken.sol";
import "./Task.sol";
import "./library/PLCRVoting.sol";
import "./library/Division.sol";
import "./library/SafeMath.sol";
import "./library/Ownable.sol";
/**
@title Reputation Registry for Distribute Network
@author Team: Jessica Marshall, Ashoka Finley
@notice This contract manages the reputation balances of each user and serves as the interface through
which users stake reputation, come to consensus around tasks, claim tasks, vote, refund their stakes,
and claim their task rewards. This contract also registers users and instantiates their accounts with 10.000 reputation
@dev This contract must be initialized with the address of a valid HyphaToken, ProjectRegistry,
and PLCR Voting contract
*/
// ===================================================================== //
//
// ===================================================================== //
contract ReputationRegistry is Ownable {
using ProjectLibrary for address;
using SafeMath for uint256;
// =====================================================================
// EVENTS
// =====================================================================
event LogRegister(
address indexed account
);
event LogProjectCreated(address projectAddress, uint256 weiCost, uint256 reputationCost);
event LogStakedReputation(address indexed projectAddress, uint256 reputation, address staker, bool projectStaked);
event LogUnstakedReputation(address indexed projectAddress, uint256 reputation, address unstaker);
event LogReputationVoteCommitted(address indexed projectAddress, uint256 index, uint256 votes, bytes32 secretHash, uint256 pollId, address voter);
event LogReputationVoteRevealed(address indexed projectAddress, uint256 index, uint256 vote, uint256 salt, address voter);
event LogReputationVoteRescued(address indexed projectAddress, uint256 index, uint256 pollId, address voter);
// =====================================================================
// STATE VARIABLES
// =====================================================================
HyphaToken hyphaToken;
ProjectRegistry projectRegistry;
PLCRVoting plcrVoting;
struct User {
uint balance;
bool registered; //indicates if address has registerd
uint lastAccess;
}
mapping (address => User) public users;
// make this a struct and save the mapping
uint256 public totalSupply; //total supply of reputation in all states
uint256 public totalUsers;
uint256 proposeProportion = 20 * 10000000000; // tokensupply/proposeProportion is the number of tokens the proposer must stake
uint256 rewardProportion = 100;
uint256 public initialRepVal = 10000;
bool freeze;
// =====================================================================
// MODIFIERS
// =====================================================================
modifier onlyPR() {
require(msg.sender == address(projectRegistry));
_;
}
// =====================================================================
// CONSTRUCTOR
// =====================================================================
/**
@dev Quasi contstructor is called after contract is deployed, must be called with hyphaToken,
projectRegistry, and plcrVoting intialized to 0
@param _hyphaToken Address of HyphaToken contract
@param _projectRegistry Address of ProjectRegistry contract
@param _plcrVoting Address of PLCRVoting contract
*/
function init(address payable _hyphaToken, address _projectRegistry, address _plcrVoting) public {
require(
address(hyphaToken) == address(0) &&
address(projectRegistry) == address(0) &&
address(plcrVoting) == address(0)
);
projectRegistry = ProjectRegistry(_projectRegistry);
plcrVoting = PLCRVoting(_plcrVoting);
hyphaToken = HyphaToken(_hyphaToken);
}
// =====================================================================
// UTILITY
// =====================================================================
/**
@notice Return the average reputation balance of the network users
@return Average balance of each user
*/
function averageBalance() external view returns(uint256) {
return totalSupply.div(totalUsers);
}
// =====================================================================
// OWNABLE
// =====================================================================
/**
* @dev Freezes the contract and allows existing token holders to withdraw tokens
*/
function freezeContract() external onlyOwner {
freeze = true;
}
/**
* @dev Unfreezes the contract and allows existing token holders to withdraw tokens
*/
function unfreezeContract() external onlyOwner {
freeze = false;
}
/**
* @dev Instantiate a new instance of plcrVoting contract
* @param _newPlcrVoting Address of the new plcr contract
*/
function updatePLCRVoting(address _newPlcrVoting) external onlyOwner {
plcrVoting = PLCRVoting(_newPlcrVoting);
}
/**
* @dev Update the address of the hyphaToken
* @param _newHyphaToken Address of the new distribute token
*/
function updateHyphaToken(address payable _newHyphaToken) external onlyOwner {
hyphaToken = HyphaToken(_newHyphaToken);
}
/**
* @dev Update the address of the base product proxy contract
* @param _newProjectRegistry Address of the new project contract
*/
function updateProjectRegistry(address _newProjectRegistry) external onlyOwner {
projectRegistry = ProjectRegistry(_newProjectRegistry);
}
function squaredAmount(uint _amount) internal pure returns (uint) {
return _amount.mul(_amount);
}
// =====================================================================
// START UP
// =====================================================================
/**
@notice Register an account `msg.sender` for the first time in the reputation registry, grant 10,000
reputation to start.
@dev Has no sybil protection, thus a user can auto generate accounts to receive excess reputation.
*/
function register() external {
require(!freeze);
require(users[msg.sender].balance == 0 && users[msg.sender].registered == false);
users[msg.sender].registered = true;
users[msg.sender].balance = initialRepVal;
totalSupply = totalSupply.add(initialRepVal);
totalUsers = totalUsers.add(1);
emit LogRegister(msg.sender);
}
// =====================================================================
// PROPOSE
// =====================================================================
/**
@notice Propose a project of cost `_cost` with staking period `_stakingPeriod` and hash `_ipfsHash`,
with reputation.
@dev Calls ProjectRegistry.createProject finalize transaction
@param _cost Total project cost in wei
@param _stakingPeriod Length of time the project can be staked before it expires
@param _ipfsHash Hash of the project description
*/
function proposeProject(uint256 _cost, uint256 _stakingPeriod, bytes calldata _ipfsHash) external {
require(!freeze);
require(block.timestamp < _stakingPeriod && _cost > 0);
uint256 costProportion = Division.percent(_cost, hyphaToken.weiBal(), 10);
uint256 proposerReputationCost = ( //divide by 20 to get 5 percent of reputation
Division.percent(costProportion, proposeProportion, 10) *
totalSupply) /
10000000000;
require(users[msg.sender].balance >= proposerReputationCost);
users[msg.sender].balance -= proposerReputationCost;
address projectAddress = projectRegistry.createProject(
_cost,
costProportion,
_stakingPeriod,
msg.sender,
2,
proposerReputationCost,
_ipfsHash
);
emit LogProjectCreated(projectAddress, _cost, proposerReputationCost);
}
/**
@notice Refund a reputation proposer upon proposal success, transfer 1% of the project cost in
wei as a reward along with any reputation staked.
@param _projectAddress Address of the project
*/
function refundProposer(address payable _projectAddress) external {
require(!freeze);
Project project = Project(_projectAddress); //called by proposer to get refund once project is active
require(project.proposer() == msg.sender);
require(project.proposerType() == 2);
uint256[2] memory proposerVals = projectRegistry.refundProposer(_projectAddress, msg.sender); //call project to "send back" staked tokens to put in proposer's balances
users[msg.sender].balance += proposerVals[1];
hyphaToken.transferWeiTo(msg.sender, proposerVals[0] / 20);
}
// =====================================================================
// STAKE
// =====================================================================
/**
@notice Stake `_reputation` reputation on project at `_projectAddress`
@dev Prevents over staking and returns any excess reputation staked.
@param _projectAddress Address of the project
@param _reputation Amount of reputation to stake
*/
function stakeReputation(address payable _projectAddress, uint256 _reputation) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
require(users[msg.sender].balance >= _reputation && _reputation > 0); //make sure project exists & RH has tokens to stake
Project project = Project(_projectAddress);
// handles edge case where someone attempts to stake past the staking deadline
projectRegistry.checkStaked(_projectAddress);
require(project.state() == 1);
uint256 repRemaining = project.reputationCost() - project.reputationStaked();
uint256 reputationVal = _reputation < repRemaining ? _reputation : repRemaining;
users[msg.sender].balance -= reputationVal;
Project(_projectAddress).stakeReputation(msg.sender, reputationVal);
bool staked = projectRegistry.checkStaked(_projectAddress);
emit LogStakedReputation(_projectAddress, _reputation, msg.sender, staked);
}
/**
@notice Unstake `_reputation` reputation from project at `_projectAddress`
@dev Require reputation to be unstaked to be greater than 0
@param _projectAddress Address of the project
@param _reputation Amount of reputation to unstake
*/
function unstakeReputation(address payable _projectAddress, uint256 _reputation) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
require(_reputation > 0);
// handles edge case where someone attempts to stake past the staking deadline
projectRegistry.checkStaked(_projectAddress);
users[msg.sender].balance += _reputation;
Project(_projectAddress).unstakeReputation(msg.sender, _reputation);
emit LogUnstakedReputation(_projectAddress, _reputation, msg.sender);
}
/**
@notice Calculates the relative weight of an `_address`.
Weighting is calculated by the proportional amount of both reputation and tokens that have been
staked on the project.
@dev Returns an average of the token staking and reputation staking to understand the relative influence of a staker
@param _address Address of the staker
@return The relative weight of a staker as a whole integer
*/
function calculateWeightOfAddress(
address _address
) public view returns (uint256) {
return Division.percent(users[_address].balance, totalSupply, 15);
}
// =====================================================================
// TASK
// =====================================================================
/**
@notice Claim a task at index `_index` from project at `_projectAddress` with description
`_taskDescription` and weighting `_weighting`
@dev Requires the reputation of msg.sender to be greater than the reputationVal of the task
@param _projectAddress Address of the project
@param _index Index of the task
@param _taskDescription Description of the task
@param _weighting Weighting of the task
*/
function claimTask(
address payable _projectAddress,
uint256 _index,
bytes32 _taskDescription,
uint _weighting
) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
Project project = Project(_projectAddress);
require(project.hashListSubmitted() == true);
uint reputationVal = project.reputationCost() * _weighting / 100;
require(users[msg.sender].balance >= reputationVal);
uint weiVal = project.proposedCost() * _weighting / 100;
users[msg.sender].balance -= reputationVal;
projectRegistry.claimTask(
_projectAddress,
_index,
_taskDescription,
msg.sender,
_weighting,
weiVal,
reputationVal
);
}
/**
@notice Reward the claimer of a task that has been successfully validated.
@param _projectAddress Address of the project
@param _index Index of the task
*/
// called by reputation holder who completed a task
function rewardTask(address payable _projectAddress, uint256 _index) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 reward = ProjectLibrary.claimTaskReward(_projectAddress, _index, msg.sender);
users[msg.sender].balance += reward;
}
// =====================================================================
// VOTING
// =====================================================================
/**
@notice First part of voting process. Commits a vote using reputation to task at index `_index`
of project at `projectAddress` for reputation `_reputation`. Submits a secrect hash `_secretHash`,
which is a tightly packed hash of the voters choice and their salt
@param _projectAddress Address of the project
@param _index Index of the task
@param _votes Reputation to vote with
@param _secretHash Secret Hash of voter choice and salt
@param _prevPollID The nonce of the previous poll. This is stored off chain
*/
function voteCommit(
address payable _projectAddress,
uint256 _index,
uint256 _votes,
bytes32 _secretHash,
uint256 _prevPollID
) external { //_secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order), done off-chain
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 pollId = Task(Project(_projectAddress).tasks(_index)).pollId();
//calculate available tokens for voting
uint256 availableVotes = plcrVoting.getAvailableTokens(msg.sender, 2);
//make sure msg.sender has tokens available in PLCR contract
//if not, request voting rights for token holder
if (availableVotes < _votes) {
uint votesCost = squaredAmount(_votes).sub(squaredAmount(availableVotes));
require(users[msg.sender].balance >= votesCost);
users[msg.sender].balance -= votesCost;
plcrVoting.requestVotingRights(msg.sender, _votes - availableVotes);
}
plcrVoting.commitVote(msg.sender, pollId, _secretHash, _votes, _prevPollID);
emit LogReputationVoteCommitted(_projectAddress, _index, _votes, _secretHash, pollId, msg.sender);
}
/**
@notice Second part of voting process. Reveal existing vote.
@param _projectAddress Address of the project
@param _index Index of the task
@param _voteOption Vote choice of account
@param _salt Salt of account
*/
function voteReveal(
address payable _projectAddress,
uint256 _index,
uint256 _voteOption,
uint256 _salt
) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
plcrVoting.revealVote(msg.sender, Task(Project(_projectAddress).tasks(_index)).pollId(), _voteOption, _salt);
emit LogReputationVoteRevealed(_projectAddress, _index, _voteOption, _salt, msg.sender);
}
/**
@notice Withdraw voting rights from PLCR Contract
@param _votes Amount of reputation to withdraw
*/
function refundVotingReputation(uint256 _votes) external {
require(!freeze);
uint userVotes = plcrVoting.getAvailableTokens(msg.sender, 2);
require(_votes <= userVotes);
uint votesPrice = squaredAmount(userVotes) - squaredAmount(userVotes - _votes);
plcrVoting.withdrawVotingRights(msg.sender, _votes);
users[msg.sender].balance += votesPrice;
}
// =====================================================================
// COMPLETE
// =====================================================================
/**
@notice Refund a reputation staker from project at `_projectAddress`
@param _projectAddress Address of the project
*/
function refundStaker(address payable _projectAddress) external { //called by worker who staked or voted
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 refund = ProjectLibrary.refundStaker(_projectAddress, msg.sender, address(this));
require(refund > 0);
Project(_projectAddress).clearReputationStake(msg.sender);
users[msg.sender].balance = users[msg.sender].balance.add(refund);
if (Project(_projectAddress).state() == 6) {
uint256 reward = refund / 2;
users[msg.sender].balance = users[msg.sender].balance.add(reward);
totalSupply = totalSupply.add(reward);
}
}
/**
@notice Rescue unrevealed reputation votes from expired polls of task at `_index` of project at
`_projectAddress`
@param _projectAddress Address of the project
@param _index Index of the task
*/
function rescueTokens(address payable _projectAddress, uint _index) external {
require(!freeze);
require(projectRegistry.projects(_projectAddress) == true);
uint256 pollId = Task(Project(_projectAddress).tasks(_index)).pollId();
plcrVoting.rescueTokens(msg.sender, pollId);
emit LogReputationVoteRescued(_projectAddress, _index, pollId, msg.sender);
}
// =====================================================================
// FAILED
// =====================================================================
/**
@notice Burn reputation in event of project failure
@dev Only callable by the ProjectRegistry contract
@param _reputation Amount of reputation to burn
*/
function burnReputation(uint256 _reputation) external onlyPR {
require(!freeze);
totalSupply -= _reputation;
}
}
| Instantiate a new instance of plcrVoting contract _newPlcrVoting Address of the new plcr contract/ | function updatePLCRVoting(address _newPlcrVoting) external onlyOwner {
plcrVoting = PLCRVoting(_newPlcrVoting);
}
| 12,682,191 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/[email protected]/token/ERC721/ERC721.sol";
import "@openzeppelin/[email protected]/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/[email protected]/utils/Counters.sol";
import "@openzeppelin/[email protected]/utils/math/SafeMath.sol";
import "@openzeppelin/[email protected]/utils/structs/EnumerableSet.sol";
import "../governance/RoleControl.sol";
import "../interfaces/IThemisEarlyFarmingNFTDescriptor.sol";
import "../interfaces/IThemisEarlyFarmingNFTStorage.sol";
import "../interfaces/IThemisEarlyFarming.sol";
contract ThemisEarlyFarmingNFT is IThemisEarlyFarmingNFTStorage,ERC721, ERC721Enumerable,RoleControl {
using Counters for Counters.Counter;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.UintSet;
event WithdrawAmountsEvent(address indexed sender,WithdrawNftParams withdrawNftParams);
event SetThemisEarlyFarmingNFTDescriptorEvent(address indexed sender,address beforeAddr,address afterAddr);
Counters.Counter private _tokenIdCounter;
address public immutable miner;
address public themisEarlyFarmingNFTDescriptor;
mapping(uint256 => EarlyFarmingNftInfo) public earlyFarmingNftInfos;
mapping(address => mapping(uint256 =>EnumerableSet.UintSet)) userNftPeriodPoolIdAllTokenIds; // user address => periodPoolId =>periodPoolId set // all records
modifier onlyMinerVistor {
require(address(miner) == msg.sender, "not miner allow.");
_;
}
constructor(address themisEarlyFarming) ERC721("Themis vaults position", "TMS-POS") {
_governance = msg.sender;
_grantRole(PAUSER_ROLE, msg.sender);
miner = themisEarlyFarming;
}
function setThemisEarlyFarmingNFTDescriptor(address addr) external onlyGovernance{
address beforeAddr = themisEarlyFarmingNFTDescriptor;
themisEarlyFarmingNFTDescriptor = addr;
emit SetThemisEarlyFarmingNFTDescriptorEvent(msg.sender,beforeAddr,addr);
}
function nftUnlockAmount(uint256 tokenId) external view returns(uint256 unlockAmount){
unlockAmount = _nftUnlockAmount(tokenId);
}
function _nftUnlockAmount(uint256 tokenId) internal view returns(uint256 unlockAmount){
EarlyFarmingNftInfo memory nftInfo = earlyFarmingNftInfos[tokenId];
uint256 currBlock = block.number;
if(nftInfo.lastUnlockBlock < currBlock
&& nftInfo.pledgeAmount > nftInfo.withdrawAmount
&& nftInfo.lastUnlockBlock <= nftInfo.endBlock){
if( currBlock < nftInfo.endBlock){
unlockAmount = nftInfo.perBlockUnlockAmount.mul(currBlock.sub(nftInfo.lastUnlockBlock));
}else{
unlockAmount = nftInfo.pledgeAmount.sub(nftInfo.withdrawAmount);
}
}
}
function withdrawUnlockAmounts(WithdrawNftParams memory withdrawNftParams) external onlyMinerVistor{
uint256 tokenId = withdrawNftParams.tokenId;
//withdrawUnlockAmount == 0 only harvest profit.
if(withdrawNftParams.withdrawUnlockAmount > 0){
require(_nftUnlockAmount(tokenId) >= withdrawNftParams.withdrawUnlockAmount,"error nft unlock amount.");
}
EarlyFarmingNftInfo storage nftInfo = earlyFarmingNftInfos[tokenId];
uint256 withdrawBlock = withdrawNftParams.withdrawUnlockAmount.div(nftInfo.perBlockUnlockAmount);
require(withdrawNftParams.user == nftInfo.ownerUser, "caller is not owner.");
nftInfo.lastInterestsShare = withdrawNftParams.lastInterestsShare;
nftInfo.lastRewardsShare = withdrawNftParams.lastRewardsShare;
if(withdrawNftParams.withdrawUnlockAmount > 0){
nftInfo.withdrawAmount += withdrawNftParams.withdrawUnlockAmount;
nftInfo.lastUnlockBlock += withdrawBlock;
if( nftInfo.lastUnlockBlock > nftInfo.endBlock){
nftInfo.lastUnlockBlock = nftInfo.endBlock;
}
}
emit WithdrawAmountsEvent(msg.sender,withdrawNftParams);
}
function safeMint(address to,EarlyFarmingNftInfo memory nftInfo) public onlyMinerVistor {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
earlyFarmingNftInfos[tokenId] = nftInfo;
earlyFarmingNftInfos[tokenId].perBlockUnlockAmount = nftInfo.pledgeAmount.div(nftInfo.endBlock.sub(nftInfo.startBlock));
userNftPeriodPoolIdAllTokenIds[nftInfo.ownerUser][nftInfo.periodPoolId].add(tokenId);
_safeMint(to, tokenId);
}
function getUserNftPeriodPoolIdAllTokenIds(address _user,uint8 _periodPoolId) external view returns(uint256[] memory){
EnumerableSet.UintSet storage _periodPoolIdTokenIds = userNftPeriodPoolIdAllTokenIds[_user][_periodPoolId];
uint256[] memory _tokenIds = new uint256[](_periodPoolIdTokenIds.length());
for (uint256 i = 0; i < _periodPoolIdTokenIds.length(); i++) {
_tokenIds[i] = _periodPoolIdTokenIds.at(i);
}
return _tokenIds;
}
function burn(uint256 tokenId) external whenNotPaused{
require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved");
_burn(tokenId);
}
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory){
if(themisEarlyFarmingNFTDescriptor == address(0)){
return super.tokenURI(tokenId);
}else{
return IThemisEarlyFarmingNFTDescriptor(themisEarlyFarmingNFTDescriptor).tokenURI(tokenId);
}
}
// function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool){
// return _isApprovedOrOwner(spender,tokenId);
// }
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override(ERC721) whenNotPaused{
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_updateNftInfo(tokenId,from,to);
super._transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override(ERC721) whenNotPaused{
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override(ERC721) whenNotPaused{
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_updateNftInfo(tokenId,from,to);
super._safeTransfer(from, to, tokenId, _data);
}
function _updateNftInfo(uint256 tokenId,address from,address to) internal{
EarlyFarmingNftInfo storage nftInfo = earlyFarmingNftInfos[tokenId];
address nftOwner = nftInfo.ownerUser;
userNftPeriodPoolIdAllTokenIds[nftOwner][nftInfo.periodPoolId].remove(tokenId);
nftInfo.ownerUser = to;
userNftPeriodPoolIdAllTokenIds[to][nftInfo.periodPoolId].add(tokenId);
IThemisEarlyFarming(miner).nftTransferCall(nftInfo.periodPoolId,from,to,nftInfo.pledgeAmount.sub(nftInfo.withdrawAmount));
}
// The following functions are overrides required by Solidity.
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)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| See {IERC721-safeTransferFrom}./ | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override(ERC721) whenNotPaused{
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_updateNftInfo(tokenId,from,to);
super._safeTransfer(from, to, tokenId, _data);
}
| 13,063,559 |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(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 MUL16(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 DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(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 TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING | function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { | 1,018,976 |
pragma solidity ^0.4.24;
interface token {
function transfer(address receiver, uint256 amount) external;
function balanceOf(address _address) external returns(uint256);
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract ZNTZLTDistributionTest is Ownable {
bool public isLive = true;
string public name = "ZNT-ZLT Distribution Test";
address public beneficiary;
uint256 public rateOfZNT = 500000;
uint256 public rateOfZLT = 3000;
uint256 public amountEthRaised = 0;
uint256 public availableZNT;
uint256 public availableZLT;
token public tokenZNT;
token public tokenZLT;
mapping(address => uint256) public donationOf;
constructor() public {
beneficiary = msg.sender;
}
// Callback function, distribute tokens to sender when ETH donation is recieved
function () payable public {
require(isLive);
uint256 donation = msg.value;
uint256 amountZNT = donation * rateOfZNT;
uint256 amountZLT = donation * rateOfZLT;
require(availableZNT >= amountZNT && availableZLT >= amountZLT);
donationOf[msg.sender] += donation;
amountEthRaised += donation;
availableZNT -= amountZNT;
availableZLT -= amountZLT;
tokenZNT.transfer(msg.sender, amountZNT);
tokenZLT.transfer(msg.sender, amountZLT);
beneficiary.transfer(donation);
}
// Halts or resumes the distribution process
function toggleIsLive() public onlyOwner {
if(isLive) {
isLive = false;
} else {
isLive = true;
}
}
// Withdraw available token in this contract
function withdrawAvailableToken(address _address, uint256 amountZNT, uint256 amountZLT) public onlyOwner {
require(availableZNT >= amountZNT && availableZLT >= amountZLT);
availableZNT -= amountZNT;
availableZLT -= amountZLT;
tokenZNT.transfer(_address, amountZNT);
tokenZLT.transfer(_address, amountZLT);
}
// Set token rate per ETH donation/contribution
function setTokensPerEth(uint256 rateZNT, uint256 rateZLT) public onlyOwner {
rateOfZNT = rateZNT;
rateOfZLT = rateZLT;
}
// Set token contract addresses of tokens involved in distribution
function setTokenReward(address _addressZNT, address _addressZLT) public onlyOwner {
tokenZNT = token(_addressZNT);
tokenZLT = token(_addressZLT);
setAvailableToken();
}
// Set the available token balance of this contract
function setAvailableToken() public onlyOwner {
availableZNT = tokenZNT.balanceOf(this);
availableZLT = tokenZLT.balanceOf(this);
}
// Set the available token balance of this contract manually
function setAvailableTokenManually(uint256 amountZNT, uint256 amountZLT) public onlyOwner {
availableZNT = amountZNT;
availableZLT = amountZLT;
}
} | Withdraw available token in this contract | function withdrawAvailableToken(address _address, uint256 amountZNT, uint256 amountZLT) public onlyOwner {
require(availableZNT >= amountZNT && availableZLT >= amountZLT);
availableZNT -= amountZNT;
availableZLT -= amountZLT;
tokenZNT.transfer(_address, amountZNT);
tokenZLT.transfer(_address, amountZLT);
}
| 1,763,359 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
contract citizen
{
string name = 'Citizen';
address public state_gov;// The address of the state government
uint internal organizationsLength = 0;
// Definition of a proposal
struct Proposal
{
uint organizationId; // Id of organization submitting the proposal
uint contId; // Id of the proposal
uint costEstimate; // Estimated cost of this proposal
string proposalDescription; // A description of the proposal
string proposalTitle; // Title of the proposal
bool is_awarded;
/*uint duration; // in months
uint epoch; // in seconds
*/
}
// Definition of a task
struct Task
{
uint taskId; //Id of the task
string taskTitle; //Title of the task
/*
string taskDescription; // a description of the task
*/
uint propId; // proposal chosen for this taskDescription
uint numVotes;
uint status;// (0-100) level of completion
bool is_completed ;
/*
uint propSubmisssionDeadline;
uint executionDeadline;
*/
uint[] taskProposalsId;// proposalId's of proposals received for the given task
}
struct Organization
{
address payable organizationAddress;// hash key for org
uint organizationId;
string organizationTitle;
// uint[] organizationProposalsId; // proposalId's of proposals submitted by this organization
}
//Definition of county
struct County
{
address countyAddress; // hash key for county
string countyTitle; // title of county
uint countyId; // Id of county
uint[] countyTasksId; // List of Ids of tasks involved with county
}
//Definition of Contract
struct Contract {
uint countyId; // Id of county involved with Contract
uint taskId; // Id of task for which contract is registred
bool isIssued;
uint votes;
uint[] ProposalIds;
mapping (address => bool) voted;
}
// Definition of Vote
struct Vote
{
uint contId; // contract for which votes are being cast
uint vote_points; // vote points voted
}
//Definition of citizen
struct Citizen
{
address citizenAddress; // Address if the citizen
string citizenName;
uint citizenId;
// indices of votes which this citizen has cast votes for
}
// Definition of Authority
struct Authority
{
address authorityAddress;
string authorityName;
uint authorityId;
uint authWeight;
uint[] authVote;
}
//Definition of payment
struct Payment
{
address to; //Address of receiver
uint cost; // Amount Payed
}
County[] public countys; //List of Countys registered with state
Task[] public tasks; //List of Tasks registered with state
// Organization[] public organizations; //List of Organizations registered with state
Proposal[] public proposals; //List of Proposals registered by the Organizations
Citizen[] public citizens; // List of Citizens enrolled with state
Authority[] public auths; //List of Authorities enrolled with state
Vote[] public votes; //List of votes cast about task completion
Contract[] public contracts; //List of contracts registered
Payment[] public payments; //List of payments tansacted
mapping(address => uint) tag; //A Dictionary of address mapped to respective category of user
// i.e , state_gov - 1, county -2, organization -3, citizen -4
mapping(uint => uint) winners; // List consisting of organizations which have been awarded contracts
//mapping(address => bool) voted;
// Dictionary from id's to array indices
mapping(uint => uint) countyMap;// countydId to index in county
mapping(uint => Organization) internal organizations; // orgI to index in organizations
mapping(uint => uint) taskMap;// taskId to index in tasks
mapping(uint => uint) propMap;// propId to index in proposals
mapping(string => uint) citiMap;// citiId to index in citizens
//mapping(uint => bool) // mapping from contract Id to bool
constructor() public
{
// state_gov = msg.sender;
tag[msg.sender] = 1;
}
function registerTask(uint task_id, string memory task_title) public
{
require(msg.sender == state_gov);
uint[] memory empArr;
tasks.push(Task({taskId:task_id, taskTitle:task_title, numVotes:0, propId:0, status:0, is_completed: false, taskProposalsId:empArr}));
taskMap[task_id] = tasks.length-1;
}
// Registering a County
function registerCounty(address county_address, uint county_Id, string memory county_Title) public
{
require(msg.sender == state_gov);
uint[] memory empArr;
countys.push(County({ countyAddress:county_address, countyId: county_Id, countyTitle:county_Title, countyTasksId:empArr}));
countyMap[county_Id] = countys.length - 1;
tag[county_address] = 2;
}
// Passing a contract from state government to a particular county
function passContract(uint task_id, uint county_id) public
{
uint[] memory emp;
contracts.push(Contract({countyId: county_id, taskId: task_id, isIssued: false, votes: 0, ProposalIds: emp}));
countys[countyMap[county_id]].countyTasksId.push(contracts.length-1);
}
// Registering organizations with the state governments
function registerOrganization(address payable org_address, uint org_Id, string memory org_title) public
{
organizations[organizationsLength] = Organization( org_address, org_Id, org_title);
organizationsLength++;
// require(msg.sender == state_gov);
// uint[] memory empArr;
// organizations.push(Organization({organizationAddress:org_address, organizationId:org_Id, organizationTitle: org_title, organizationProposalsId:empArr}));
// orgMap[org_Id] = organizations.length-1;
// tag[org_address] = 3;
}
//Issue a particular contract
function issueContract(uint cont_id) public
{
require(tag[msg.sender] == 2);
contracts[cont_id].isIssued = true;
}
//Registering new proposals
function registerProposal(uint org_Id, uint cont_Id, string memory prop_Desc, string memory prop_Title, uint cost) public
{
require(tag[msg.sender] == 3 && contracts[cont_Id].isIssued);
proposals.push(Proposal({organizationId:org_Id, contId:cont_Id, is_awarded:false, proposalDescription:prop_Desc, proposalTitle:prop_Title, costEstimate: cost}));
contracts[cont_Id].ProposalIds.push(proposals.length-1);
// the current proposal has to be added to the respective organization
// organizations[orgMap[org_Id]].organizationProposalsId.push(proposals.length-1);
}
//Choosing the winning Proposal
function winningProposal(uint cont_Id, uint prop_Id) public
{
require(msg.sender==state_gov);
bool found = false;
for (uint i = 0; i < contracts[cont_Id].ProposalIds.length; i++)
if (contracts[cont_Id].ProposalIds[i] == prop_Id)
found = true;
require(found);
proposals[prop_Id].is_awarded = true;
winners[cont_Id] = prop_Id;
}
//Registering new Citizens
function registerCitizen(address cit_address, uint cit_Id, string memory cit_Name) public
{
require(msg.sender == state_gov);
citizens.push(Citizen({citizenAddress:cit_address, citizenName: cit_Name, citizenId: cit_Id}));
citiMap[cit_Name] = citizens.length-1;
tag[cit_address] = 4;
}
// Accepting Votes for a particular task
function taskingVote(uint cont_Id,bool vote) public
{
// ensuring that the vote is cast by either a citizen or government and the contract is issued
require((tag[msg.sender] == 2 || tag[msg.sender] == 4 ) && contracts[cont_Id].isIssued && !contracts[cont_Id].voted[msg.sender]);
/*
TODO :
1. Take care of case when votes are being cast for task that is not awarded yet
2. Take care of citizen voting on the same task multiple times
//*/
uint weight = 1;
if (tag[msg.sender] == 2)
weight = 5;
votes.push(Vote({ contId:cont_Id, vote_points:weight}));
contracts[cont_Id].voted[msg.sender] = true;
if (vote == true)
contracts[cont_Id].votes += weight;
else
contracts[cont_Id].votes -= weight;
}
// Function to verify completion of the contract
function verifyCompletion(uint cont_id) view public returns (bool)
{
require(msg.sender==state_gov);
if (contracts[cont_id].votes > 0)
return true;
else
return false;
}
//Function to pay the organization post completion of contract
function payment (uint cont_id) public
{
// payment can be done only by the state_gov
require(verifyCompletion(cont_id));
payments.push(Payment(organizations[proposals[winners[cont_id]].organizationId].organizationAddress, proposals[winners[cont_id]].costEstimate));
}
} | Registering new Citizens | function registerCitizen(address cit_address, uint cit_Id, string memory cit_Name) public
{
require(msg.sender == state_gov);
citiMap[cit_Name] = citizens.length-1;
tag[cit_address] = 4;
}
| 7,265,938 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../Euler.sol";
import "../Storage.sol";
import "../modules/EToken.sol";
import "../modules/Markets.sol";
import "../BaseIRMLinearKink.sol";
import "../vendor/RPow.sol";
interface IExec {
function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice);
function getPrice(address underlying) external view returns (uint twap, uint twapPeriod);
function detailedLiquidity(address account) external view returns (IRiskManager.AssetLiquidity[] memory assets);
function liquidity(address account) external view returns (IRiskManager.LiquidityStatus memory status);
}
contract EulerGeneralView is Constants {
bytes32 immutable public moduleGitCommit;
constructor(bytes32 moduleGitCommit_) {
moduleGitCommit = moduleGitCommit_;
}
// Query
struct Query {
address eulerContract;
address account;
address[] markets;
}
// Response
struct ResponseMarket {
// Universal
address underlying;
string name;
string symbol;
uint8 decimals;
address eTokenAddr;
address dTokenAddr;
address pTokenAddr;
Storage.AssetConfig config;
uint poolSize;
uint totalBalances;
uint totalBorrows;
uint reserveBalance;
uint32 reserveFee;
uint borrowAPY;
uint supplyAPY;
// Pricing
uint twap;
uint twapPeriod;
uint currPrice;
uint16 pricingType;
uint32 pricingParameters;
address pricingForwarded;
// Account specific
uint underlyingBalance;
uint eulerAllowance;
uint eTokenBalance;
uint eTokenBalanceUnderlying;
uint dTokenBalance;
IRiskManager.LiquidityStatus liquidityStatus;
}
struct Response {
uint timestamp;
uint blockNumber;
ResponseMarket[] markets;
address[] enteredMarkets;
}
// Implementation
function doQueryBatch(Query[] memory qs) external view returns (Response[] memory r) {
r = new Response[](qs.length);
for (uint i = 0; i < qs.length; ++i) {
r[i] = doQuery(qs[i]);
}
}
function doQuery(Query memory q) public view returns (Response memory r) {
r.timestamp = block.timestamp;
r.blockNumber = block.number;
Euler eulerProxy = Euler(q.eulerContract);
Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS));
IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC));
IRiskManager.AssetLiquidity[] memory liqs;
if (q.account != address(0)) {
liqs = execProxy.detailedLiquidity(q.account);
}
r.markets = new ResponseMarket[](liqs.length + q.markets.length);
for (uint i = 0; i < liqs.length; ++i) {
ResponseMarket memory m = r.markets[i];
m.underlying = liqs[i].underlying;
m.liquidityStatus = liqs[i].status;
populateResponseMarket(q, m, marketsProxy, execProxy);
}
for (uint j = liqs.length; j < liqs.length + q.markets.length; ++j) {
uint i = j - liqs.length;
ResponseMarket memory m = r.markets[j];
m.underlying = q.markets[i];
populateResponseMarket(q, m, marketsProxy, execProxy);
}
if (q.account != address(0)) {
r.enteredMarkets = marketsProxy.getEnteredMarkets(q.account);
}
}
function populateResponseMarket(Query memory q, ResponseMarket memory m, Markets marketsProxy, IExec execProxy) private view {
m.name = getStringOrBytes32(m.underlying, IERC20.name.selector);
m.symbol = getStringOrBytes32(m.underlying, IERC20.symbol.selector);
m.decimals = IERC20(m.underlying).decimals();
m.eTokenAddr = marketsProxy.underlyingToEToken(m.underlying);
if (m.eTokenAddr == address(0)) return; // not activated
m.dTokenAddr = marketsProxy.eTokenToDToken(m.eTokenAddr);
m.pTokenAddr = marketsProxy.underlyingToPToken(m.underlying);
{
Storage.AssetConfig memory c = marketsProxy.underlyingToAssetConfig(m.underlying);
m.config = c;
}
m.poolSize = IERC20(m.underlying).balanceOf(q.eulerContract);
m.totalBalances = EToken(m.eTokenAddr).totalSupplyUnderlying();
m.totalBorrows = IERC20(m.dTokenAddr).totalSupply();
m.reserveBalance = EToken(m.eTokenAddr).reserveBalanceUnderlying();
m.reserveFee = marketsProxy.reserveFee(m.underlying);
{
uint borrowSPY = uint(int(marketsProxy.interestRate(m.underlying)));
(m.borrowAPY, m.supplyAPY) = computeAPYs(borrowSPY, m.totalBorrows, m.totalBalances, m.reserveFee);
}
(m.twap, m.twapPeriod, m.currPrice) = execProxy.getPriceFull(m.underlying);
(m.pricingType, m.pricingParameters, m.pricingForwarded) = marketsProxy.getPricingConfig(m.underlying);
if (q.account == address(0)) return;
m.underlyingBalance = IERC20(m.underlying).balanceOf(q.account);
m.eTokenBalance = IERC20(m.eTokenAddr).balanceOf(q.account);
m.eTokenBalanceUnderlying = EToken(m.eTokenAddr).balanceOfUnderlying(q.account);
m.dTokenBalance = IERC20(m.dTokenAddr).balanceOf(q.account);
m.eulerAllowance = IERC20(m.underlying).allowance(q.account, q.eulerContract);
}
function computeAPYs(uint borrowSPY, uint totalBorrows, uint totalBalancesUnderlying, uint32 reserveFee) public pure returns (uint borrowAPY, uint supplyAPY) {
borrowAPY = RPow.rpow(borrowSPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27;
uint supplySPY = totalBalancesUnderlying == 0 ? 0 : borrowSPY * totalBorrows / totalBalancesUnderlying;
supplySPY = supplySPY * (RESERVE_FEE_SCALE - reserveFee) / RESERVE_FEE_SCALE;
supplyAPY = RPow.rpow(supplySPY + 1e27, SECONDS_PER_YEAR, 10**27) - 1e27;
}
// Interest rate model queries
struct QueryIRM {
address eulerContract;
address underlying;
}
struct ResponseIRM {
uint kink;
uint baseAPY;
uint kinkAPY;
uint maxAPY;
uint baseSupplyAPY;
uint kinkSupplyAPY;
uint maxSupplyAPY;
}
function doQueryIRM(QueryIRM memory q) external view returns (ResponseIRM memory r) {
Euler eulerProxy = Euler(q.eulerContract);
Markets marketsProxy = Markets(eulerProxy.moduleIdToProxy(MODULEID__MARKETS));
uint moduleId = marketsProxy.interestRateModel(q.underlying);
address moduleImpl = eulerProxy.moduleIdToImplementation(moduleId);
BaseIRMLinearKink irm = BaseIRMLinearKink(moduleImpl);
uint kink = r.kink = irm.kink();
uint32 reserveFee = marketsProxy.reserveFee(q.underlying);
uint baseSPY = irm.baseRate();
uint kinkSPY = baseSPY + (kink * irm.slope1());
uint maxSPY = kinkSPY + ((type(uint32).max - kink) * irm.slope2());
(r.baseAPY, r.baseSupplyAPY) = computeAPYs(baseSPY, 0, type(uint32).max, reserveFee);
(r.kinkAPY, r.kinkSupplyAPY) = computeAPYs(kinkSPY, kink, type(uint32).max, reserveFee);
(r.maxAPY, r.maxSupplyAPY) = computeAPYs(maxSPY, type(uint32).max, type(uint32).max, reserveFee);
}
// AccountLiquidity queries
struct ResponseAccountLiquidity {
IRiskManager.AssetLiquidity[] markets;
}
function doQueryAccountLiquidity(address eulerContract, address[] memory addrs) external view returns (ResponseAccountLiquidity[] memory r) {
Euler eulerProxy = Euler(eulerContract);
IExec execProxy = IExec(eulerProxy.moduleIdToProxy(MODULEID__EXEC));
r = new ResponseAccountLiquidity[](addrs.length);
for (uint i = 0; i < addrs.length; ++i) {
r[i].markets = execProxy.detailedLiquidity(addrs[i]);
}
}
// For tokens like MKR which return bytes32 on name() or symbol()
function getStringOrBytes32(address contractAddress, bytes4 selector) private view returns (string memory) {
(bool success, bytes memory result) = contractAddress.staticcall(abi.encodeWithSelector(selector));
if (!success) return "";
return result.length == 32 ? string(abi.encodePacked(result)) : abi.decode(result, (string));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Base.sol";
/// @notice Main storage contract for the Euler system
contract Euler is Base {
constructor(address admin, address installerModule) {
emit Genesis();
reentrancyLock = REENTRANCYLOCK__UNLOCKED;
upgradeAdmin = admin;
governorAdmin = admin;
moduleLookup[MODULEID__INSTALLER] = installerModule;
address installerProxy = _createProxy(MODULEID__INSTALLER);
trustedSenders[installerProxy].moduleImpl = installerModule;
}
string public constant name = "Euler Protocol";
/// @notice Lookup the current implementation contract for a module
/// @param moduleId Fixed constant that refers to a module type (ie MODULEID__ETOKEN)
/// @return An internal address specifies the module's implementation code
function moduleIdToImplementation(uint moduleId) external view returns (address) {
return moduleLookup[moduleId];
}
/// @notice Lookup a proxy that can be used to interact with a module (only valid for single-proxy modules)
/// @param moduleId Fixed constant that refers to a module type (ie MODULEID__MARKETS)
/// @return An address that should be cast to the appropriate module interface, ie IEulerMarkets(moduleIdToProxy(2))
function moduleIdToProxy(uint moduleId) external view returns (address) {
return proxyLookup[moduleId];
}
function dispatch() external {
uint32 moduleId = trustedSenders[msg.sender].moduleId;
address moduleImpl = trustedSenders[msg.sender].moduleImpl;
require(moduleId != 0, "e/sender-not-trusted");
if (moduleImpl == address(0)) moduleImpl = moduleLookup[moduleId];
uint msgDataLength = msg.data.length;
require(msgDataLength >= (4 + 4 + 20), "e/input-too-short");
assembly {
let payloadSize := sub(calldatasize(), 4)
calldatacopy(0, 4, payloadSize)
mstore(payloadSize, shl(96, caller()))
let result := delegatecall(gas(), moduleImpl, 0, add(payloadSize, 20), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Constants.sol";
abstract contract Storage is Constants {
// Dispatcher and upgrades
uint reentrancyLock;
address upgradeAdmin;
address governorAdmin;
mapping(uint => address) moduleLookup; // moduleId => module implementation
mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules)
struct TrustedSenderInfo {
uint32 moduleId; // 0 = un-trusted
address moduleImpl; // only non-zero for external single-proxy modules
}
mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted)
// Account-level state
// Sub-accounts are considered distinct accounts
struct AccountStorage {
// Packed slot: 1 + 5 + 4 + 20 = 30
uint8 deferLiquidityStatus;
uint40 lastAverageLiquidityUpdate;
uint32 numMarketsEntered;
address firstMarketEntered;
uint averageLiquidity;
address averageLiquidityDelegate;
}
mapping(address => AccountStorage) accountLookup;
mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered;
// Markets and assets
struct AssetConfig {
// Packed slot: 20 + 1 + 4 + 4 + 3 = 32
address eTokenAddress;
bool borrowIsolated;
uint32 collateralFactor;
uint32 borrowFactor;
uint24 twapWindow;
}
struct UserAsset {
uint112 balance;
uint144 owed;
uint interestAccumulator;
}
struct AssetStorage {
// Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32
uint40 lastInterestAccumulatorUpdate;
uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot
uint32 interestRateModel;
int96 interestRate;
uint32 reserveFee;
uint16 pricingType;
uint32 pricingParameters;
address underlying;
uint96 reserveBalance;
address dTokenAddress;
uint112 totalBalances;
uint144 totalBorrows;
uint interestAccumulator;
mapping(address => UserAsset) users;
mapping(address => mapping(address => uint)) eTokenAllowance;
mapping(address => mapping(address => uint)) dTokenAllowance;
}
mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig
mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage
mapping(address => address) internal dTokenLookup; // DToken => EToken
mapping(address => address) internal pTokenLookup; // PToken => underlying
mapping(address => address) internal reversePTokenLookup; // underlying => PToken
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../BaseLogic.sol";
/// @notice Tokenised representation of assets
contract EToken is BaseLogic {
constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__ETOKEN, moduleGitCommit_) {}
function CALLER() private view returns (address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) {
(msgSender, proxyAddr) = unpackTrailingParams();
assetStorage = eTokenLookup[proxyAddr];
underlying = assetStorage.underlying;
require(underlying != address(0), "e/unrecognized-etoken-caller");
}
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// External methods
/// @notice Pool name, ie "Euler Pool: DAI"
function name() external view returns (string memory) {
(address underlying,,,) = CALLER();
return string(abi.encodePacked("Euler Pool: ", IERC20(underlying).name()));
}
/// @notice Pool symbol, ie "eDAI"
function symbol() external view returns (string memory) {
(address underlying,,,) = CALLER();
return string(abi.encodePacked("e", IERC20(underlying).symbol()));
}
/// @notice Decimals, always normalised to 18.
function decimals() external pure returns (uint8) {
return 18;
}
/// @notice Address of underlying asset
function underlyingAsset() external view returns (address) {
(address underlying,,,) = CALLER();
return underlying;
}
/// @notice Sum of all balances, in internal book-keeping units (non-increasing)
function totalSupply() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.totalBalances;
}
/// @notice Sum of all balances, in underlying units (increases as interest is earned)
function totalSupplyUnderlying() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetCache.totalBalances) / assetCache.underlyingDecimalsScaler;
}
/// @notice Balance of a particular account, in internal book-keeping units (non-increasing)
function balanceOf(address account) external view returns (uint) {
(, AssetStorage storage assetStorage,,) = CALLER();
return assetStorage.users[account].balance;
}
/// @notice Balance of a particular account, in underlying units (increases as interest is earned)
function balanceOfUnderlying(address account) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetStorage.users[account].balance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Balance of the reserves, in internal book-keeping units (non-increasing)
function reserveBalance() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.reserveBalance;
}
/// @notice Balance of the reserves, in underlying units (increases as interest is earned)
function reserveBalanceUnderlying() external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, assetCache.reserveBalance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Convert an eToken balance to an underlying amount, taking into account current exchange rate
/// @param balance eToken balance, in internal book-keeping units (18 decimals)
/// @return Amount in underlying units, (same decimals as underlying token)
function convertBalanceToUnderlying(uint balance) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return balanceToUnderlyingAmount(assetCache, balance) / assetCache.underlyingDecimalsScaler;
}
/// @notice Convert an underlying amount to an eToken balance, taking into account current exchange rate
/// @param underlyingAmount Amount in underlying units (same decimals as underlying token)
/// @return eToken balance, in internal book-keeping units (18 decimals)
function convertUnderlyingToBalance(uint underlyingAmount) external view returns (uint) {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return underlyingAmountToBalance(assetCache, decodeExternalAmount(assetCache, underlyingAmount));
}
/// @notice Updates interest accumulator and totalBorrows, credits reserves, re-targets interest rate, and logs asset status
function touch() external nonReentrant {
(address underlying, AssetStorage storage assetStorage,,) = CALLER();
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
updateInterestRate(assetStorage, assetCache);
logAssetStatus(assetCache);
}
/// @notice Transfer underlying tokens from sender to the Euler pool, and increase account's eTokens
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 for full underlying token balance)
function deposit(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestDeposit(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
if (amount == type(uint).max) {
amount = callBalanceOf(assetCache, msgSender);
}
amount = decodeExternalAmount(assetCache, amount);
uint amountTransferred = pullTokens(assetCache, msgSender, amount);
uint amountInternal;
// pullTokens() updates poolSize in the cache, but we need the poolSize before the deposit to determine
// the internal amount so temporarily reduce it by the amountTransferred (which is size checked within
// pullTokens()). We can't compute this value before the pull because we don't know how much we'll
// actually receive (the token might be deflationary).
unchecked {
assetCache.poolSize -= amountTransferred;
amountInternal = underlyingAmountToBalance(assetCache, amountTransferred);
assetCache.poolSize += amountTransferred;
}
increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
if (assetStorage.users[account].owed != 0) checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Transfer underlying tokens from Euler pool to sender, and decrease account's eTokens
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 for full pool balance)
function withdraw(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestWithdraw(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
uint amountInternal;
(amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount);
require(assetCache.poolSize >= amount, "e/insufficient-pool-size");
pushTokens(assetCache, msgSender, amount);
decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Mint eTokens and a corresponding amount of dTokens ("self-borrow")
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units
function mint(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestMint(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
amount = decodeExternalAmount(assetCache, amount);
uint amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
amount = balanceToUnderlyingAmount(assetCache, amountInternal);
// Mint ETokens
increaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
// Mint DTokens
increaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Pay off dToken liability with eTokens ("self-repay")
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param amount In underlying units (use max uint256 to repay the debt in full or up to the available underlying balance)
function burn(uint subAccountId, uint amount) external nonReentrant {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
updateAverageLiquidity(account);
emit RequestBurn(account, amount);
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
uint owed = getCurrentOwed(assetStorage, assetCache, account);
if (owed == 0) return;
uint amountInternal;
(amount, amountInternal) = withdrawAmounts(assetStorage, assetCache, account, amount);
if (amount > owed) {
amount = owed;
amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
}
// Burn ETokens
decreaseBalance(assetStorage, assetCache, proxyAddr, account, amountInternal);
// Burn DTokens
decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, amount);
checkLiquidity(account);
logAssetStatus(assetCache);
}
/// @notice Allow spender to access an amount of your eTokens in sub-account 0
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approve(address spender, uint amount) external reentrantOK returns (bool) {
return approveSubAccount(0, spender, amount);
}
/// @notice Allow spender to access an amount of your eTokens in a particular sub-account
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approveSubAccount(uint subAccountId, address spender, uint amount) public reentrantOK returns (bool) {
(, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
address account = getSubAccount(msgSender, subAccountId);
require(!isSubAccountOf(spender, account), "e/self-approval");
assetStorage.eTokenAllowance[account][spender] = amount;
emitViaProxy_Approval(proxyAddr, account, spender, amount);
return true;
}
/// @notice Retrieve the current allowance
/// @param holder Xor with the desired sub-account ID (if applicable)
/// @param spender Trusted address
function allowance(address holder, address spender) external view returns (uint) {
(, AssetStorage storage assetStorage,,) = CALLER();
return assetStorage.eTokenAllowance[holder][spender];
}
/// @notice Transfer eTokens to another address (from sub-account 0)
/// @param to Xor with the desired sub-account ID (if applicable)
/// @param amount In internal book-keeping units (as returned from balanceOf).
function transfer(address to, uint amount) external returns (bool) {
return transferFrom(address(0), to, amount);
}
/// @notice Transfer the full eToken balance of an address to another
/// @param from This address must've approved the to address, or be a sub-account of msg.sender
/// @param to Xor with the desired sub-account ID (if applicable)
function transferFromMax(address from, address to) external returns (bool) {
(, AssetStorage storage assetStorage,,) = CALLER();
return transferFrom(from, to, assetStorage.users[from].balance);
}
/// @notice Transfer eTokens from one address to another
/// @param from This address must've approved the to address, or be a sub-account of msg.sender
/// @param to Xor with the desired sub-account ID (if applicable)
/// @param amount In internal book-keeping units (as returned from balanceOf).
function transferFrom(address from, address to, uint amount) public nonReentrant returns (bool) {
(address underlying, AssetStorage storage assetStorage, address proxyAddr, address msgSender) = CALLER();
AssetCache memory assetCache = loadAssetCache(underlying, assetStorage);
if (from == address(0)) from = msgSender;
require(from != to, "e/self-transfer");
updateAverageLiquidity(from);
updateAverageLiquidity(to);
emit RequestTransferEToken(from, to, amount);
if (amount == 0) return true;
if (!isSubAccountOf(msgSender, from) && assetStorage.eTokenAllowance[from][msgSender] != type(uint).max) {
require(assetStorage.eTokenAllowance[from][msgSender] >= amount, "e/insufficient-allowance");
unchecked { assetStorage.eTokenAllowance[from][msgSender] -= amount; }
emitViaProxy_Approval(proxyAddr, from, msgSender, assetStorage.eTokenAllowance[from][msgSender]);
}
transferBalance(assetStorage, assetCache, proxyAddr, from, to, amount);
checkLiquidity(from);
if (assetStorage.users[to].owed != 0) checkLiquidity(to);
logAssetStatus(assetCache);
return true;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "../BaseLogic.sol";
import "../IRiskManager.sol";
import "../PToken.sol";
/// @notice Activating and querying markets, and maintaining entered markets lists
contract Markets is BaseLogic {
constructor(bytes32 moduleGitCommit_) BaseLogic(MODULEID__MARKETS, moduleGitCommit_) {}
/// @notice Create an Euler pool and associated EToken and DToken addresses.
/// @param underlying The address of an ERC20-compliant token. There must be an initialised uniswap3 pool for the underlying/reference asset pair.
/// @return The created EToken, or the existing EToken if already activated.
function activateMarket(address underlying) external nonReentrant returns (address) {
require(pTokenLookup[underlying] == address(0), "e/markets/invalid-token");
return doActivateMarket(underlying);
}
function doActivateMarket(address underlying) private returns (address) {
// Pre-existing
if (underlyingLookup[underlying].eTokenAddress != address(0)) return underlyingLookup[underlying].eTokenAddress;
// Validation
require(trustedSenders[underlying].moduleId == 0 && underlying != address(this), "e/markets/invalid-token");
uint8 decimals = IERC20(underlying).decimals();
require(decimals <= 18, "e/too-many-decimals");
// Get risk manager parameters
IRiskManager.NewMarketParameters memory params;
{
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER,
abi.encodeWithSelector(IRiskManager.getNewMarketParameters.selector, underlying));
(params) = abi.decode(result, (IRiskManager.NewMarketParameters));
}
// Create proxies
address childEToken = params.config.eTokenAddress = _createProxy(MODULEID__ETOKEN);
address childDToken = _createProxy(MODULEID__DTOKEN);
// Setup storage
underlyingLookup[underlying] = params.config;
dTokenLookup[childDToken] = childEToken;
AssetStorage storage assetStorage = eTokenLookup[childEToken];
assetStorage.underlying = underlying;
assetStorage.pricingType = params.pricingType;
assetStorage.pricingParameters = params.pricingParameters;
assetStorage.dTokenAddress = childDToken;
assetStorage.lastInterestAccumulatorUpdate = uint40(block.timestamp);
assetStorage.underlyingDecimals = decimals;
assetStorage.interestRateModel = uint32(MODULEID__IRM_DEFAULT);
assetStorage.reserveFee = type(uint32).max; // default
assetStorage.interestAccumulator = INITIAL_INTEREST_ACCUMULATOR;
emit MarketActivated(underlying, childEToken, childDToken);
return childEToken;
}
/// @notice Create a pToken and activate it on Euler. pTokens are protected wrappers around assets that prevent borrowing.
/// @param underlying The address of an ERC20-compliant token. There must already be an activated market on Euler for this underlying, and it must have a non-zero collateral factor.
/// @return The created pToken, or an existing one if already activated.
function activatePToken(address underlying) external nonReentrant returns (address) {
require(pTokenLookup[underlying] == address(0), "e/nested-ptoken");
if (reversePTokenLookup[underlying] != address(0)) return reversePTokenLookup[underlying];
{
AssetConfig memory config = resolveAssetConfig(underlying);
require(config.collateralFactor != 0, "e/ptoken/not-collateral");
}
address pTokenAddr = address(new PToken(address(this), underlying));
pTokenLookup[pTokenAddr] = underlying;
reversePTokenLookup[underlying] = pTokenAddr;
emit PTokenActivated(underlying, pTokenAddr);
doActivateMarket(pTokenAddr);
return pTokenAddr;
}
// General market accessors
/// @notice Given an underlying, lookup the associated EToken
/// @param underlying Token address
/// @return EToken address, or address(0) if not activated
function underlyingToEToken(address underlying) external view returns (address) {
return underlyingLookup[underlying].eTokenAddress;
}
/// @notice Given an underlying, lookup the associated DToken
/// @param underlying Token address
/// @return DToken address, or address(0) if not activated
function underlyingToDToken(address underlying) external view returns (address) {
return eTokenLookup[underlyingLookup[underlying].eTokenAddress].dTokenAddress;
}
/// @notice Given an underlying, lookup the associated PToken
/// @param underlying Token address
/// @return PToken address, or address(0) if it doesn't exist
function underlyingToPToken(address underlying) external view returns (address) {
return reversePTokenLookup[underlying];
}
/// @notice Looks up the Euler-related configuration for a token, and resolves all default-value placeholders to their currently configured values.
/// @param underlying Token address
/// @return Configuration struct
function underlyingToAssetConfig(address underlying) external view returns (AssetConfig memory) {
return resolveAssetConfig(underlying);
}
/// @notice Looks up the Euler-related configuration for a token, and returns it unresolved (with default-value placeholders)
/// @param underlying Token address
/// @return config Configuration struct
function underlyingToAssetConfigUnresolved(address underlying) external view returns (AssetConfig memory config) {
config = underlyingLookup[underlying];
require(config.eTokenAddress != address(0), "e/market-not-activated");
}
/// @notice Given an EToken address, looks up the associated underlying
/// @param eToken EToken address
/// @return underlying Token address
function eTokenToUnderlying(address eToken) external view returns (address underlying) {
underlying = eTokenLookup[eToken].underlying;
require(underlying != address(0), "e/invalid-etoken");
}
/// @notice Given an EToken address, looks up the associated DToken
/// @param eToken EToken address
/// @return dTokenAddr DToken address
function eTokenToDToken(address eToken) external view returns (address dTokenAddr) {
dTokenAddr = eTokenLookup[eToken].dTokenAddress;
require(dTokenAddr != address(0), "e/invalid-etoken");
}
function getAssetStorage(address underlying) private view returns (AssetStorage storage) {
address eTokenAddr = underlyingLookup[underlying].eTokenAddress;
require(eTokenAddr != address(0), "e/market-not-activated");
return eTokenLookup[eTokenAddr];
}
/// @notice Looks up an asset's currently configured interest rate model
/// @param underlying Token address
/// @return Module ID that represents the interest rate model (IRM)
function interestRateModel(address underlying) external view returns (uint) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.interestRateModel;
}
/// @notice Retrieves the current interest rate for an asset
/// @param underlying Token address
/// @return The interest rate in yield-per-second, scaled by 10**27
function interestRate(address underlying) external view returns (int96) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.interestRate;
}
/// @notice Retrieves the current interest rate accumulator for an asset
/// @param underlying Token address
/// @return An opaque accumulator that increases as interest is accrued
function interestAccumulator(address underlying) external view returns (uint) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
AssetCache memory assetCache = loadAssetCacheRO(underlying, assetStorage);
return assetCache.interestAccumulator;
}
/// @notice Retrieves the reserve fee in effect for an asset
/// @param underlying Token address
/// @return Amount of interest that is redirected to the reserves, as a fraction scaled by RESERVE_FEE_SCALE (4e9)
function reserveFee(address underlying) external view returns (uint32) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
return assetStorage.reserveFee == type(uint32).max ? uint32(DEFAULT_RESERVE_FEE) : assetStorage.reserveFee;
}
/// @notice Retrieves the pricing config for an asset
/// @param underlying Token address
/// @return pricingType (1=pegged, 2=uniswap3, 3=forwarded)
/// @return pricingParameters If uniswap3 pricingType then this represents the uniswap pool fee used, otherwise unused
/// @return pricingForwarded If forwarded pricingType then this is the address prices are forwarded to, otherwise address(0)
function getPricingConfig(address underlying) external view returns (uint16 pricingType, uint32 pricingParameters, address pricingForwarded) {
AssetStorage storage assetStorage = getAssetStorage(underlying);
pricingType = assetStorage.pricingType;
pricingParameters = assetStorage.pricingParameters;
pricingForwarded = pricingType == PRICINGTYPE__FORWARDED ? pTokenLookup[underlying] : address(0);
}
// Enter/exit markets
/// @notice Retrieves the list of entered markets for an account (assets enabled for collateral or borrowing)
/// @param account User account
/// @return List of underlying token addresses
function getEnteredMarkets(address account) external view returns (address[] memory) {
return getEnteredMarketsArray(account);
}
/// @notice Add an asset to the entered market list, or do nothing if already entered
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param newMarket Underlying token address
function enterMarket(uint subAccountId, address newMarket) external nonReentrant {
address msgSender = unpackTrailingParamMsgSender();
address account = getSubAccount(msgSender, subAccountId);
require(underlyingLookup[newMarket].eTokenAddress != address(0), "e/market-not-activated");
doEnterMarket(account, newMarket);
}
/// @notice Remove an asset from the entered market list, or do nothing if not already present
/// @param subAccountId 0 for primary, 1-255 for a sub-account
/// @param oldMarket Underlying token address
function exitMarket(uint subAccountId, address oldMarket) external nonReentrant {
address msgSender = unpackTrailingParamMsgSender();
address account = getSubAccount(msgSender, subAccountId);
AssetConfig memory config = resolveAssetConfig(oldMarket);
AssetStorage storage assetStorage = eTokenLookup[config.eTokenAddress];
uint balance = assetStorage.users[account].balance;
uint owed = assetStorage.users[account].owed;
require(owed == 0, "e/outstanding-borrow");
doExitMarket(account, oldMarket);
if (config.collateralFactor != 0 && balance != 0) {
checkLiquidity(account);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseIRM.sol";
contract BaseIRMLinearKink is BaseIRM {
uint public immutable baseRate;
uint public immutable slope1;
uint public immutable slope2;
uint public immutable kink;
constructor(uint moduleId_, bytes32 moduleGitCommit_, uint baseRate_, uint slope1_, uint slope2_, uint kink_) BaseIRM(moduleId_, moduleGitCommit_) {
baseRate = baseRate_;
slope1 = slope1_;
slope2 = slope2_;
kink = kink_;
}
function computeInterestRateImpl(address, uint32 utilisation) internal override view returns (int96) {
uint ir = baseRate;
if (utilisation <= kink) {
ir += utilisation * slope1;
} else {
ir += kink * slope1;
ir += slope2 * (utilisation - kink);
}
return int96(int(ir));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// From MakerDAO DSS
// Copyright (C) 2018 Rain <[email protected]>
//
// 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.8.0;
library RPow {
function rpow(uint x, uint n, uint base) internal 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)
}
}
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
//import "hardhat/console.sol"; // DEV_MODE
import "./Storage.sol";
import "./Events.sol";
import "./Proxy.sol";
abstract contract Base is Storage, Events {
// Modules
function _createProxy(uint proxyModuleId) internal returns (address) {
require(proxyModuleId != 0, "e/create-proxy/invalid-module");
require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module");
// If we've already created a proxy for a single-proxy module, just return it:
if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId];
// Otherwise create a proxy:
address proxyAddr = address(new Proxy());
if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr;
trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) });
emit ProxyCreated(proxyAddr, proxyModuleId);
return proxyAddr;
}
function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) {
(bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input);
if (!success) revertBytes(result);
return result;
}
// Modifiers
modifier nonReentrant() {
require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy");
reentrancyLock = REENTRANCYLOCK__LOCKED;
_;
reentrancyLock = REENTRANCYLOCK__UNLOCKED;
}
modifier reentrantOK() { // documentation only
_;
}
// Used to flag functions which do not modify storage, but do perform a delegate call
// to a view function, which prohibits a standard view modifier. The flag is used to
// patch state mutability in compiled ABIs and interfaces.
modifier staticDelegate() {
_;
}
// WARNING: Must be very careful with this modifier. It resets the free memory pointer
// to the value it was when the function started. This saves gas if more memory will
// be allocated in the future. However, if the memory will be later referenced
// (for example because the function has returned a pointer to it) then you cannot
// use this modifier.
modifier FREEMEM() {
uint origFreeMemPtr;
assembly {
origFreeMemPtr := mload(0x40)
}
_;
/*
assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs
let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF
for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) }
}
*/
assembly {
mstore(0x40, origFreeMemPtr)
}
}
// Error handling
function revertBytes(bytes memory errMsg) internal pure {
if (errMsg.length > 0) {
assembly {
revert(add(32, errMsg), mload(errMsg))
}
}
revert("e/empty-error");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Storage.sol";
abstract contract Events {
event Genesis();
event ProxyCreated(address indexed proxy, uint moduleId);
event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken);
event PTokenActivated(address indexed underlying, address indexed pToken);
event EnterMarket(address indexed underlying, address indexed account);
event ExitMarket(address indexed underlying, address indexed account);
event Deposit(address indexed underlying, address indexed account, uint amount);
event Withdraw(address indexed underlying, address indexed account, uint amount);
event Borrow(address indexed underlying, address indexed account, uint amount);
event Repay(address indexed underlying, address indexed account, uint amount);
event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount);
event TrackAverageLiquidity(address indexed account);
event UnTrackAverageLiquidity(address indexed account);
event DelegateAverageLiquidity(address indexed account, address indexed delegate);
event PTokenWrap(address indexed underlying, address indexed account, uint amount);
event PTokenUnWrap(address indexed underlying, address indexed account, uint amount);
event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp);
event RequestDeposit(address indexed account, uint amount);
event RequestWithdraw(address indexed account, uint amount);
event RequestMint(address indexed account, uint amount);
event RequestBurn(address indexed account, uint amount);
event RequestTransferEToken(address indexed from, address indexed to, uint amount);
event RequestBorrow(address indexed account, uint amount);
event RequestRepay(address indexed account, uint amount);
event RequestTransferDToken(address indexed from, address indexed to, uint amount);
event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield);
event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin);
event InstallerSetGovernorAdmin(address indexed newGovernorAdmin);
event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit);
event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig);
event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams);
event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter);
event GovSetReserveFee(address indexed underlying, uint32 newReserveFee);
event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount);
event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
contract Proxy {
address immutable creator;
constructor() {
creator = msg.sender;
}
// External interface
fallback() external {
address creator_ = creator;
if (msg.sender == creator_) {
assembly {
mstore(0, 0)
calldatacopy(31, 0, calldatasize())
switch mload(0) // numTopics
case 0 { log0(32, sub(calldatasize(), 1)) }
case 1 { log1(64, sub(calldatasize(), 33), mload(32)) }
case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) }
case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) }
case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) }
default { revert(0, 0) }
return(0, 0)
}
} else {
assembly {
mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector
calldatacopy(4, 0, calldatasize())
mstore(add(4, calldatasize()), shl(96, caller()))
let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
abstract contract Constants {
// Universal
uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar
// Protocol parameters
uint internal constant MAX_SANE_AMOUNT = type(uint112).max;
uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max;
uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max;
uint internal constant INTERNAL_DEBT_PRECISION = 1e9;
uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account
uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered
uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32
uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32
uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000);
uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27;
uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60;
uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144;
uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60;
uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000);
uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000);
// Implementation internals
uint internal constant REENTRANCYLOCK__UNLOCKED = 1;
uint internal constant REENTRANCYLOCK__LOCKED = 2;
uint8 internal constant DEFERLIQUIDITY__NONE = 0;
uint8 internal constant DEFERLIQUIDITY__CLEAN = 1;
uint8 internal constant DEFERLIQUIDITY__DIRTY = 2;
// Pricing types
uint16 internal constant PRICINGTYPE__PEGGED = 1;
uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2;
uint16 internal constant PRICINGTYPE__FORWARDED = 3;
// Modules
// Public single-proxy modules
uint internal constant MODULEID__INSTALLER = 1;
uint internal constant MODULEID__MARKETS = 2;
uint internal constant MODULEID__LIQUIDATION = 3;
uint internal constant MODULEID__GOVERNANCE = 4;
uint internal constant MODULEID__EXEC = 5;
uint internal constant MODULEID__SWAP = 6;
uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999;
// Public multi-proxy modules
uint internal constant MODULEID__ETOKEN = 500_000;
uint internal constant MODULEID__DTOKEN = 500_001;
uint internal constant MAX_EXTERNAL_MODULEID = 999_999;
// Internal modules
uint internal constant MODULEID__RISK_MANAGER = 1_000_000;
// Interest rate models
// Default for new markets
uint internal constant MODULEID__IRM_DEFAULT = 2_000_000;
// Testing-only
uint internal constant MODULEID__IRM_ZERO = 2_000_001;
uint internal constant MODULEID__IRM_FIXED = 2_000_002;
uint internal constant MODULEID__IRM_LINEAR = 2_000_100;
// Classes
uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500;
uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501;
uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502;
uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503;
// Swap types
uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1;
uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4;
uint internal constant SWAP_TYPE__1INCH = 5;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6;
uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseModule.sol";
import "./BaseIRM.sol";
import "./Interfaces.sol";
import "./Utils.sol";
import "./vendor/RPow.sol";
import "./IRiskManager.sol";
abstract contract BaseLogic is BaseModule {
constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {}
// Account auth
function getSubAccount(address primary, uint subAccountId) internal pure returns (address) {
require(subAccountId < 256, "e/sub-account-id-too-big");
return address(uint160(primary) ^ uint160(subAccountId));
}
function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) {
return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF);
}
// Entered markets array
function getEnteredMarketsArray(address account) internal view returns (address[] memory) {
uint32 numMarketsEntered = accountLookup[account].numMarketsEntered;
address firstMarketEntered = accountLookup[account].firstMarketEntered;
address[] memory output = new address[](numMarketsEntered);
if (numMarketsEntered == 0) return output;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
output[0] = firstMarketEntered;
for (uint i = 1; i < numMarketsEntered; ++i) {
output[i] = markets[i];
}
return output;
}
function isEnteredInMarket(address account, address underlying) internal view returns (bool) {
uint32 numMarketsEntered = accountLookup[account].numMarketsEntered;
address firstMarketEntered = accountLookup[account].firstMarketEntered;
if (numMarketsEntered == 0) return false;
if (firstMarketEntered == underlying) return true;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
for (uint i = 1; i < numMarketsEntered; ++i) {
if (markets[i] == underlying) return true;
}
return false;
}
function doEnterMarket(address account, address underlying) internal {
AccountStorage storage accountStorage = accountLookup[account];
uint32 numMarketsEntered = accountStorage.numMarketsEntered;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
if (numMarketsEntered != 0) {
if (accountStorage.firstMarketEntered == underlying) return; // already entered
for (uint i = 1; i < numMarketsEntered; i++) {
if (markets[i] == underlying) return; // already entered
}
}
require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets");
if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying;
else markets[numMarketsEntered] = underlying;
accountStorage.numMarketsEntered = numMarketsEntered + 1;
emit EnterMarket(underlying, account);
}
// Liquidity check must be done by caller after calling this
function doExitMarket(address account, address underlying) internal {
AccountStorage storage accountStorage = accountLookup[account];
uint32 numMarketsEntered = accountStorage.numMarketsEntered;
address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account];
uint searchIndex = type(uint).max;
if (numMarketsEntered == 0) return; // already exited
if (accountStorage.firstMarketEntered == underlying) {
searchIndex = 0;
} else {
for (uint i = 1; i < numMarketsEntered; i++) {
if (markets[i] == underlying) {
searchIndex = i;
break;
}
}
if (searchIndex == type(uint).max) return; // already exited
}
uint lastMarketIndex = numMarketsEntered - 1;
if (searchIndex != lastMarketIndex) {
if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex];
else markets[searchIndex] = markets[lastMarketIndex];
}
accountStorage.numMarketsEntered = uint32(lastMarketIndex);
if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund
emit ExitMarket(underlying, account);
}
// AssetConfig
function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) {
AssetConfig memory config = underlyingLookup[underlying];
require(config.eTokenAddress != address(0), "e/market-not-activated");
if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR;
if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS;
return config;
}
// AssetCache
struct AssetCache {
address underlying;
uint112 totalBalances;
uint144 totalBorrows;
uint96 reserveBalance;
uint interestAccumulator;
uint40 lastInterestAccumulatorUpdate;
uint8 underlyingDecimals;
uint32 interestRateModel;
int96 interestRate;
uint32 reserveFee;
uint16 pricingType;
uint32 pricingParameters;
uint poolSize; // result of calling balanceOf on underlying (in external units)
uint underlyingDecimalsScaler;
uint maxExternalAmount;
}
function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) {
dirty = false;
assetCache.underlying = underlying;
// Storage loads
assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate;
uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals;
assetCache.interestRateModel = assetStorage.interestRateModel;
assetCache.interestRate = assetStorage.interestRate;
assetCache.reserveFee = assetStorage.reserveFee;
assetCache.pricingType = assetStorage.pricingType;
assetCache.pricingParameters = assetStorage.pricingParameters;
assetCache.reserveBalance = assetStorage.reserveBalance;
assetCache.totalBalances = assetStorage.totalBalances;
assetCache.totalBorrows = assetStorage.totalBorrows;
assetCache.interestAccumulator = assetStorage.interestAccumulator;
// Derived state
unchecked {
assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals);
assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler;
}
uint poolSize = callBalanceOf(assetCache, address(this));
if (poolSize <= assetCache.maxExternalAmount) {
unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; }
} else {
assetCache.poolSize = 0;
}
// Update interest accumulator and reserves
if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) {
dirty = true;
uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate;
// Compute new values
uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27;
uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator;
uint newReserveBalance = assetCache.reserveBalance;
uint newTotalBalances = assetCache.totalBalances;
uint feeAmount = (newTotalBorrows - assetCache.totalBorrows)
* (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee)
/ (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION);
if (feeAmount != 0) {
uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION);
newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount);
newReserveBalance += newTotalBalances - assetCache.totalBalances;
}
// Store new values in assetCache, only if no overflows will occur
if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) {
assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows);
assetCache.interestAccumulator = newInterestAccumulator;
assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp);
if (newTotalBalances != assetCache.totalBalances) {
assetCache.reserveBalance = encodeSmallAmount(newReserveBalance);
assetCache.totalBalances = encodeAmount(newTotalBalances);
}
}
}
}
function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) {
if (initAssetCache(underlying, assetStorage, assetCache)) {
assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate;
assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot
assetStorage.reserveBalance = assetCache.reserveBalance;
assetStorage.totalBalances = assetCache.totalBalances;
assetStorage.totalBorrows = assetCache.totalBorrows;
assetStorage.interestAccumulator = assetCache.interestAccumulator;
}
}
function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) {
initAssetCache(underlying, assetStorage, assetCache);
}
// Utils
function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) {
require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large");
unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; }
}
function encodeAmount(uint amount) internal pure returns (uint112) {
require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode");
return uint112(amount);
}
function encodeSmallAmount(uint amount) internal pure returns (uint96) {
require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode");
return uint96(amount);
}
function encodeDebtAmount(uint amount) internal pure returns (uint144) {
require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode");
return uint144(amount);
}
function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) {
if (assetCache.totalBalances == 0) return 1e18;
return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances;
}
function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return amount * 1e18 / exchangeRate;
}
function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate;
}
function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) {
uint exchangeRate = computeExchangeRate(assetCache);
return amount * exchangeRate / 1e18;
}
function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) {
// We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail.
(bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account));
// If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail.
// If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0.
// Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored.
if (!success || data.length < 32) return 0;
return abi.decode(data, (uint256));
}
function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal {
uint32 utilisation;
{
uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION;
uint poolAssets = assetCache.poolSize + totalBorrows;
if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0
else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18);
}
bytes memory result = callInternalModule(assetCache.interestRateModel,
abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation));
(int96 newInterestRate) = abi.decode(result, (int96));
assetStorage.interestRate = assetCache.interestRate = newInterestRate;
}
function logAssetStatus(AssetCache memory a) internal {
emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp);
}
// Balances
function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal {
assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount);
updateInterestRate(assetStorage, assetCache);
emit Deposit(assetCache.underlying, account, amount);
emitViaProxy_Transfer(eTokenAddress, address(0), account, amount);
}
function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal {
uint origBalance = assetStorage.users[account].balance;
require(origBalance >= amount, "e/insufficient-balance");
assetStorage.users[account].balance = encodeAmount(origBalance - amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount);
updateInterestRate(assetStorage, assetCache);
emit Withdraw(assetCache.underlying, account, amount);
emitViaProxy_Transfer(eTokenAddress, account, address(0), amount);
}
function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal {
uint origFromBalance = assetStorage.users[from].balance;
require(origFromBalance >= amount, "e/insufficient-balance");
uint newFromBalance;
unchecked { newFromBalance = origFromBalance - amount; }
assetStorage.users[from].balance = encodeAmount(newFromBalance);
assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount);
emit Withdraw(assetCache.underlying, from, amount);
emit Deposit(assetCache.underlying, to, amount);
emitViaProxy_Transfer(eTokenAddress, from, to, amount);
}
function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) {
uint amountInternal;
if (amount == type(uint).max) {
amountInternal = assetStorage.users[account].balance;
amount = balanceToUnderlyingAmount(assetCache, amountInternal);
} else {
amount = decodeExternalAmount(assetCache, amount);
amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount);
}
return (amount, amountInternal);
}
// Borrows
// Returns internal precision
function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) {
// Don't bother loading the user's accumulator
if (owed == 0) return 0;
// Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator
return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator;
}
// When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid.
// unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural)
// Takes and returns 27 decimals precision.
function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) {
if (owed == 0) return 0;
unchecked {
uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler;
return (owed + scale - 1) / scale * scale;
}
}
// Returns 18-decimals precision (debt amount is rounded up)
function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) {
return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION;
}
function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) {
prevOwedExact = assetStorage.users[account].owed;
newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact);
assetStorage.users[account].owed = encodeDebtAmount(newOwedExact);
assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator;
}
function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private {
prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION;
owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION;
if (owed > prevOwed) {
uint change = owed - prevOwed;
emit Borrow(assetCache.underlying, account, change);
emitViaProxy_Transfer(dTokenAddress, address(0), account, change / assetCache.underlyingDecimalsScaler);
} else if (prevOwed > owed) {
uint change = prevOwed - owed;
emit Repay(assetCache.underlying, account, change);
emitViaProxy_Transfer(dTokenAddress, account, address(0), change / assetCache.underlyingDecimalsScaler);
}
}
function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal {
amount *= INTERNAL_DEBT_PRECISION;
require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported");
(uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account);
if (owed == 0) doEnterMarket(account, assetCache.underlying);
owed += amount;
assetStorage.users[account].owed = encodeDebtAmount(owed);
assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount);
updateInterestRate(assetStorage, assetCache);
logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed);
}
function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal {
uint amount = origAmount * INTERNAL_DEBT_PRECISION;
(uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account);
uint owedRoundedUp = roundUpOwed(assetCache, owed);
require(amount <= owedRoundedUp, "e/repay-too-much");
uint owedRemaining;
unchecked { owedRemaining = owedRoundedUp - amount; }
if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows;
assetStorage.users[account].owed = encodeDebtAmount(owedRemaining);
assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining);
updateInterestRate(assetStorage, assetCache);
logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining);
}
function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal {
uint amount = origAmount * INTERNAL_DEBT_PRECISION;
(uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from);
(uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to);
if (toOwed == 0) doEnterMarket(to, assetCache.underlying);
// If amount was rounded up, transfer exact amount owed
if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed;
require(fromOwed >= amount, "e/insufficient-balance");
unchecked { fromOwed -= amount; }
// Transfer any residual dust
if (fromOwed < INTERNAL_DEBT_PRECISION) {
amount += fromOwed;
fromOwed = 0;
}
toOwed += amount;
assetStorage.users[from].owed = encodeDebtAmount(fromOwed);
assetStorage.users[to].owed = encodeDebtAmount(toOwed);
logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed);
logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed);
}
// Reserves
function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal {
assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount);
assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount);
}
// Token asset transfers
// amounts are in underlying units
function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) {
uint poolSizeBefore = assetCache.poolSize;
Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler);
uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this)));
require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount");
unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; }
}
function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) {
uint poolSizeBefore = assetCache.poolSize;
Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler);
uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this)));
require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount");
unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; }
}
// Liquidity
function getAssetPrice(address asset) internal returns (uint) {
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset));
return abi.decode(result, (uint));
}
function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) {
bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account));
(IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus));
collateralValue = status.collateralValue;
liabilityValue = status.liabilityValue;
}
function checkLiquidity(address account) internal {
uint8 status = accountLookup[account].deferLiquidityStatus;
if (status == DEFERLIQUIDITY__NONE) {
callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account));
} else if (status == DEFERLIQUIDITY__CLEAN) {
accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY;
}
}
// Optional average liquidity tracking
function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) {
uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT;
uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration;
uint currAverageLiquidity;
{
(uint collateralValue, uint liabilityValue) = getAccountLiquidity(account);
currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0;
}
return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) +
(currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD);
}
function getUpdatedAverageLiquidity(address account) internal returns (uint) {
uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate;
if (lastAverageLiquidityUpdate == 0) return 0;
uint deltaT = block.timestamp - lastAverageLiquidityUpdate;
if (deltaT == 0) return accountLookup[account].averageLiquidity;
return computeNewAverageLiquidity(account, deltaT);
}
function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) {
address delegate = accountLookup[account].averageLiquidityDelegate;
return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account
? getUpdatedAverageLiquidity(delegate)
: getUpdatedAverageLiquidity(account);
}
function updateAverageLiquidity(address account) internal {
uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate;
if (lastAverageLiquidityUpdate == 0) return;
uint deltaT = block.timestamp - lastAverageLiquidityUpdate;
if (deltaT == 0) return;
accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp);
accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Base.sol";
abstract contract BaseModule is Base {
// Construction
// public accessors common to all modules
uint immutable public moduleId;
bytes32 immutable public moduleGitCommit;
constructor(uint moduleId_, bytes32 moduleGitCommit_) {
moduleId = moduleId_;
moduleGitCommit = moduleGitCommit_;
}
// Accessing parameters
function unpackTrailingParamMsgSender() internal pure returns (address msgSender) {
assembly {
msgSender := shr(96, calldataload(sub(calldatasize(), 40)))
}
}
function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) {
assembly {
msgSender := shr(96, calldataload(sub(calldatasize(), 40)))
proxyAddr := shr(96, calldataload(sub(calldatasize(), 20)))
}
}
// Emit logs via proxies
function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM {
(bool success,) = proxyAddr.call(abi.encodePacked(
uint8(3),
keccak256(bytes('Transfer(address,address,uint256)')),
bytes32(uint(uint160(from))),
bytes32(uint(uint160(to))),
value
));
require(success, "e/log-proxy-fail");
}
function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM {
(bool success,) = proxyAddr.call(abi.encodePacked(
uint8(3),
keccak256(bytes('Approval(address,address,uint256)')),
bytes32(uint(uint160(owner))),
bytes32(uint(uint160(spender))),
value
));
require(success, "e/log-proxy-fail");
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./BaseModule.sol";
abstract contract BaseIRM is BaseModule {
constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {}
int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR
int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0;
function computeInterestRateImpl(address, uint32) internal virtual returns (int96);
function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) {
int96 rate = computeInterestRateImpl(underlying, utilisation);
if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE;
else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE;
return rate;
}
function reset(address underlying, bytes calldata resetParams) external virtual {}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
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 IERC20Permit {
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external;
}
interface IERC3156FlashBorrower {
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32);
}
interface IERC3156FlashLender {
function maxFlashLoan(address token) external view returns (uint256);
function flashFee(address token, uint256 amount) external view returns (uint256);
function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Interfaces.sol";
library Utils {
function safeTransferFrom(address token, address from, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
function safeTransfer(address token, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
function safeApprove(address token, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Storage.sol";
// This interface is used to avoid a circular dependency between BaseLogic and RiskManager
interface IRiskManager {
struct NewMarketParameters {
uint16 pricingType;
uint32 pricingParameters;
Storage.AssetConfig config;
}
struct LiquidityStatus {
uint collateralValue;
uint liabilityValue;
uint numBorrows;
bool borrowIsolated;
}
struct AssetLiquidity {
address underlying;
LiquidityStatus status;
}
function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory);
function requireLiquidity(address account) external view;
function computeLiquidity(address account) external view returns (LiquidityStatus memory status);
function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets);
function getPrice(address underlying) external view returns (uint twap, uint twapPeriod);
function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./Interfaces.sol";
import "./Utils.sol";
/// @notice Protected Tokens are simple wrappers for tokens, allowing you to use tokens as collateral without permitting borrowing
contract PToken {
address immutable euler;
address immutable underlyingToken;
constructor(address euler_, address underlying_) {
euler = euler_;
underlyingToken = underlying_;
}
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalBalances;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
/// @notice PToken name, ie "Euler Protected DAI"
function name() external view returns (string memory) {
return string(abi.encodePacked("Euler Protected ", IERC20(underlyingToken).name()));
}
/// @notice PToken symbol, ie "pDAI"
function symbol() external view returns (string memory) {
return string(abi.encodePacked("p", IERC20(underlyingToken).symbol()));
}
/// @notice Number of decimals, which is same as the underlying's
function decimals() external view returns (uint8) {
return IERC20(underlyingToken).decimals();
}
/// @notice Address of the underlying asset
function underlying() external view returns (address) {
return underlyingToken;
}
/// @notice Balance of an account's wrapped tokens
function balanceOf(address who) external view returns (uint) {
return balances[who];
}
/// @notice Sum of all wrapped token balances
function totalSupply() external view returns (uint) {
return totalBalances;
}
/// @notice Retrieve the current allowance
/// @param holder Address giving permission to access tokens
/// @param spender Trusted address
function allowance(address holder, address spender) external view returns (uint) {
return allowances[holder][spender];
}
/// @notice Transfer your own pTokens to another address
/// @param recipient Recipient address
/// @param amount Amount of wrapped token to transfer
function transfer(address recipient, uint amount) external returns (bool) {
return transferFrom(msg.sender, recipient, amount);
}
/// @notice Transfer pTokens from one address to another. The euler address is automatically granted approval.
/// @param from This address must've approved the to address
/// @param recipient Recipient address
/// @param amount Amount to transfer
function transferFrom(address from, address recipient, uint amount) public returns (bool) {
require(balances[from] >= amount, "insufficient balance");
if (from != msg.sender && msg.sender != euler && allowances[from][msg.sender] != type(uint).max) {
require(allowances[from][msg.sender] >= amount, "insufficient allowance");
allowances[from][msg.sender] -= amount;
emit Approval(from, msg.sender, allowances[from][msg.sender]);
}
balances[from] -= amount;
balances[recipient] += amount;
emit Transfer(from, recipient, amount);
return true;
}
/// @notice Allow spender to access an amount of your pTokens. It is not necessary to approve the euler address.
/// @param spender Trusted address
/// @param amount Use max uint256 for "infinite" allowance
function approve(address spender, uint amount) external returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Convert underlying tokens to pTokens
/// @param amount In underlying units (which are equivalent to pToken units)
function wrap(uint amount) external {
Utils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);
claimSurplus(msg.sender);
}
/// @notice Convert pTokens to underlying tokens
/// @param amount In pToken units (which are equivalent to underlying units)
function unwrap(uint amount) external {
doUnwrap(msg.sender, amount);
}
// Only callable by the euler contract:
function forceUnwrap(address who, uint amount) external {
require(msg.sender == euler, "permission denied");
doUnwrap(who, amount);
}
/// @notice Claim any surplus tokens held by the PToken contract. This should only be used by contracts.
/// @param who Beneficiary to be credited for the surplus token amount
function claimSurplus(address who) public {
uint currBalance = IERC20(underlyingToken).balanceOf(address(this));
require(currBalance > totalBalances, "no surplus balance to claim");
uint amount = currBalance - totalBalances;
totalBalances += amount;
balances[who] += amount;
emit Transfer(address(0), who, amount);
}
// Internal shared:
function doUnwrap(address who, uint amount) private {
require(balances[who] >= amount, "insufficient balance");
totalBalances -= amount;
balances[who] -= amount;
Utils.safeTransfer(underlyingToken, who, amount);
emit Transfer(who, address(0), amount);
}
} | Transfer eTokens to another address (from sub-account 0) to Xor with the desired sub-account ID (if applicable) amount In internal book-keeping units (as returned from balanceOf). | function transfer(address to, uint amount) external returns (bool) {
return transferFrom(address(0), to, amount);
}
| 144,887 |
/*
Documentation: https://expopulo.readthedocs.io
Author: Brandon Chaffee
License: MIT
*/
pragma solidity ^0.4.23;
import "../imports/EscrowToken.sol";
contract Organization is EscrowToken {
///Creation of Organization
event OrganizationFormed(address creator);
// Of1 (Appendix)
function formOrganization(bytes32 _details)
validDetail(_details) public {
Organization storage o = orgs[msg.sender];
require(o.details == bytes32(0));
o.details = _details;
o.admin[msg.sender].isValid = true;
emit OrganizationFormed(msg.sender);
}
// Of2 (Appendix)
function modifyOrganization(
address _org,
bytes32 _details
) isAdmin(_org) validDetail(_details) public {
orgs[_org].details = _details;
}
// Of3 (Appendix)
function setAdminStatus(
address _org,
address _admin,
bool _status
) isAdmin(_org) public {
orgs[_org].admin[_admin].isValid = _status;
}
event ProjectCreated(address indexed creator, uint256 id);
// Of4 (Appendix)
function createProject(
address _org,
bytes32 _details
) isAdmin(_org) validDetail(_details) public returns(uint256){
Organization storage o = orgs[_org];
uint256 projectID = o.projects.length++;
o.projects[projectID].details = _details;
emit ProjectCreated(_org, projectID);
return projectID;
}
// Of5 (Appendix)
function distributeToProject(
address _org,
uint256 _project,
uint256 _amount
) isAdmin(_org) public {
Organization storage o = orgs[_org];
Project storage p = o.projects[_project];
require(o.total >= _amount);
o.total = o.total.sub(_amount);
p.distributed = p.distributed.add(_amount);
p.total = p.total.add(_amount);
}
// Of6 (Appendix)
function recallProjectDistribution(
address _org,
uint256 _project,
uint256 _amount
) isAdmin(_org) public {
Organization storage o = orgs[_org];
Project storage p = o.projects[_project];
//Can only recall amount that was from distribution
require(p.distributed >= _amount);
//Can only recall amount if it has not been collect from total
require(p.total >= _amount);
p.distributed = p.distributed.sub(_amount);
p.total = p.total.sub(_amount);
o.total = o.total.add(_amount);
}
}
| Of6 (Appendix)Can only recall amount that was from distributionCan only recall amount if it has not been collect from total | function recallProjectDistribution(
address _org,
uint256 _project,
uint256 _amount
) isAdmin(_org) public {
Organization storage o = orgs[_org];
Project storage p = o.projects[_project];
require(p.distributed >= _amount);
require(p.total >= _amount);
p.distributed = p.distributed.sub(_amount);
p.total = p.total.sub(_amount);
o.total = o.total.add(_amount);
}
| 12,534,230 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.0;
/**
* @title Lib_SafeExecutionManagerWrapper
*/
library Lib_SafeExecutionManagerWrapper {
/**********************
* Internal Functions *
**********************/
/**
* Makes an ovmCALL and performs all the necessary safety checks.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @param _gasLimit Gas limit for the call.
* @param _target Address to call.
* @param _calldata Data to send to the call.
* @return _success Whether or not the call reverted.
* @return _returndata Data returned by the call.
*/
function safeCALL(
address _ovmExecutionManager,
uint256 _gasLimit,
address _target,
bytes memory _calldata
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmCALL(uint256,address,bytes)",
_gasLimit,
_target,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Performs an ovmCREATE and the necessary safety checks.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @param _gasLimit Gas limit for the creation.
* @param _bytecode Code for the new contract.
* @return _contract Address of the created contract.
*/
function safeCREATE(
address _ovmExecutionManager,
uint256 _gasLimit,
bytes memory _bytecode
)
internal
returns (
address _contract
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
_gasLimit,
abi.encodeWithSignature(
"ovmCREATE(bytes)",
_bytecode
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmCHAINID call.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @return _CHAINID Result of calling ovmCHAINID.
*/
function safeCHAINID(
address _ovmExecutionManager
)
internal
returns (
uint256 _CHAINID
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmCHAINID()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmADDRESS call.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @return _ADDRESS Result of calling ovmADDRESS.
*/
function safeADDRESS(
address _ovmExecutionManager
)
internal
returns (
address _ADDRESS
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmGETNONCE call.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @return _nonce Result of calling ovmGETNONCE.
*/
function safeGETNONCE(
address _ovmExecutionManager
)
internal
returns (
uint256 _nonce
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmGETNONCE()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmSETNONCE call.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @param _nonce New account nonce.
*/
function safeSETNONCE(
address _ovmExecutionManager,
uint256 _nonce
)
internal
{
_safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmSETNONCE(uint256)",
_nonce
)
);
}
/*********************
* Private Functions *
*********************/
/**
* Performs an ovm interaction and the necessary safety checks.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
* @param _gasLimit Gas limit for the interaction.
* @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).
* @return _returndata Data sent back by the OVM_ExecutionManager.
*/
function _safeExecutionManagerInteraction(
address _ovmExecutionManager,
uint256 _gasLimit,
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
(
bool success,
bytes memory returndata
) = _ovmExecutionManager.call{gas: _gasLimit}(_calldata);
if (success == false) {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
} else if (returndata.length == 1) {
assembly {
return(0, 1)
}
} else {
return returndata;
}
}
function _safeExecutionManagerInteraction(
address _ovmExecutionManager,
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
return _safeExecutionManagerInteraction(
_ovmExecutionManager,
gasleft(),
_calldata
);
}
}
| Performs a safe ovmADDRESS call. _ovmExecutionManager Address of the OVM_ExecutionManager. return _ADDRESS Result of calling ovmADDRESS./ | function safeADDRESS(
address _ovmExecutionManager
)
internal
returns (
address _ADDRESS
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_ovmExecutionManager,
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
| 6,365,732 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// EIP 2612
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IERC20.sol";
library SafeERC20 {
function safeSymbol(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeName(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeDecimals(IERC20 token) public view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(IERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed");
}
function safeTransferFrom(IERC20 token, address from, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed");
}
}
// SPDX-License-Identifier: MIT
// P1 - P3: OK
pragma solidity 0.6.12;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2ERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./Ownable.sol";
// TanosiaMaker is MasterChef's left hand and kinda a wizard. He can cook up Sushi from pretty much anything!
// This contract handles "serving up" rewards for xSushi holders by trading tokens collected from fees for Sushi.
// T1 - T4: OK
contract TanosiaMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// V1 - V5: OK
IUniswapV2Factory public immutable factory;
// V1 - V5: OK
address public immutable bar;
// V1 - V5: OK
address private immutable sushi;
// V1 - V5: OK
address private immutable weth;
// V1 - V5: OK
mapping(address => address) internal _bridges;
// E1: OK
event LogBridgeSet(address indexed token, address indexed bridge);
// E1: OK
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
uint256 amount0,
uint256 amount1,
uint256 amountSUSHI
);
constructor(
address _factory,
address _bar,
address _sushi,
address _weth
) public {
factory = IUniswapV2Factory(_factory);
bar = _bar;
sushi = _sushi;
weth = _weth;
}
// F1 - F10: OK
// C1 - C24: OK
function bridgeFor(address token) public view returns (address bridge) {
bridge = _bridges[token];
if (bridge == address(0)) {
bridge = weth;
}
}
// F1 - F10: OK
// C1 - C24: OK
function setBridge(address token, address bridge) external onlyOwner {
// Checks
require(
token != sushi && token != weth && token != bridge,
"TanosiaMaker: Invalid bridge"
);
// Effects
_bridges[token] = bridge;
emit LogBridgeSet(token, bridge);
}
// M1 - M5: OK
// C1 - C24: OK
// C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
require(msg.sender == tx.origin, "TanosiaMaker: must use EOA");
_;
}
// F1 - F10: OK
// F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple
// F6: There is an exploit to add lots of SUSHI to the bar, run convert, then remove the SUSHI again.
// As the size of the SushiBar has grown, this requires large amounts of funds and isn't super profitable anymore
// The onlyEOA modifier prevents this being done with a flash loan.
// C1 - C24: OK
function convert(address token0, address token1) external onlyEOA() {
_convert(token0, token1);
}
// F1 - F10: OK, see convert
// C1 - C24: OK
// C3: Loop is under control of the caller
function convertMultiple(
address[] calldata token0,
address[] calldata token1
) external onlyEOA() {
// TODO: This can be optimized a fair bit, but this is safer and simpler for now
uint256 len = token0.length;
for (uint256 i = 0; i < len; i++) {
_convert(token0[i], token1[i]);
}
}
// F1 - F10: OK
// C1- C24: OK
function _convert(address token0, address token1) internal {
// Interactions
// S1 - S4: OK
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
require(address(pair) != address(0), "TanosiaMaker: Invalid pair");
// balanceOf: S1 - S4: OK
// transfer: X1 - X5: OK
IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
// X1 - X5: OK
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
}
emit LogConvert(
msg.sender,
token0,
token1,
amount0,
amount1,
_convertStep(token0, token1, amount0, amount1)
);
}
// F1 - F10: OK
// C1 - C24: OK
// All safeTransfer, _swap, _toSUSHI, _convertStep: X1 - X5: OK
function _convertStep(
address token0,
address token1,
uint256 amount0,
uint256 amount1
) internal returns (uint256 sushiOut) {
// Interactions
if (token0 == token1) {
uint256 amount = amount0.add(amount1);
if (token0 == sushi) {
IERC20(sushi).safeTransfer(bar, amount);
sushiOut = amount;
} else if (token0 == weth) {
sushiOut = _toSUSHI(weth, amount);
} else {
address bridge = bridgeFor(token0);
amount = _swap(token0, bridge, amount, address(this));
sushiOut = _convertStep(bridge, bridge, amount, 0);
}
} else if (token0 == sushi) {
// eg. SUSHI - ETH
IERC20(sushi).safeTransfer(bar, amount0);
sushiOut = _toSUSHI(token1, amount1).add(amount0);
} else if (token1 == sushi) {
// eg. USDT - SUSHI
IERC20(sushi).safeTransfer(bar, amount1);
sushiOut = _toSUSHI(token0, amount0).add(amount1);
} else if (token0 == weth) {
// eg. ETH - USDC
sushiOut = _toSUSHI(
weth,
_swap(token1, weth, amount1, address(this)).add(amount0)
);
} else if (token1 == weth) {
// eg. USDT - ETH
sushiOut = _toSUSHI(
weth,
_swap(token0, weth, amount0, address(this)).add(amount1)
);
} else {
// eg. MIC - USDT
address bridge0 = bridgeFor(token0);
address bridge1 = bridgeFor(token1);
if (bridge0 == token1) {
// eg. MIC - USDT - and bridgeFor(MIC) = USDT
sushiOut = _convertStep(
bridge0,
token1,
_swap(token0, bridge0, amount0, address(this)),
amount1
);
} else if (bridge1 == token0) {
// eg. WBTC - DSD - and bridgeFor(DSD) = WBTC
sushiOut = _convertStep(
token0,
bridge1,
amount0,
_swap(token1, bridge1, amount1, address(this))
);
} else {
sushiOut = _convertStep(
bridge0,
bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC
_swap(token0, bridge0, amount0, address(this)),
_swap(token1, bridge1, amount1, address(this))
);
}
}
}
// F1 - F10: OK
// C1 - C24: OK
// All safeTransfer, swap: X1 - X5: OK
function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
) internal returns (uint256 amountOut) {
// Checks
// X1 - X5: OK
IUniswapV2Pair pair =
IUniswapV2Pair(factory.getPair(fromToken, toToken));
require(address(pair) != address(0), "TanosiaMaker: Cannot convert");
// Interactions
// X1 - X5: OK
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(990);
if (fromToken == pair.token0()) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, new bytes(0));
// TODO: Add maximum slippage?
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, new bytes(0));
// TODO: Add maximum slippage?
}
}
// F1 - F10: OK
// C1 - C24: OK
function _toSUSHI(address token, uint256 amountIn)
internal
returns (uint256 amountOut)
{
// X1 - X5: OK
amountOut = _swap(token, sushi, amountIn, bar);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "SafeMath: Underflow");}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "SafeMath: Mul Overflow");}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "SafeMath: uint128 Overflow");
c = uint128(a);
}
}
library SafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, "SafeMath: Underflow");}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function 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;
}
// SPDX-License-Identifier: MIT
// Audit on 5-Jan-2021 by Keno and BoringCrypto
// P1 - P3: OK
pragma solidity 0.6.12;
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
// T1 - T4: OK
contract OwnableData {
// V1 - V5: OK
address public owner;
// V1 - V5: OK
address public pendingOwner;
}
// T1 - T4: OK
contract Ownable is OwnableData {
// E1: OK
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
// F1 - F9: OK
// C1 - C21: OK
function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
} else {
// Effects
pendingOwner = newOwner;
}
}
// F1 - F9: OK
// C1 - C21: OK
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
// M1 - M5: OK
// C1 - C21: OK
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './libraries/UniswapV2Library.sol';
import './libraries/SafeMath.sol';
import './libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Router02.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract TanosiaRouter is IUniswapV2Router02 {
using SafeMathUniswap for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: 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 (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: 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 = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(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 = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(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 = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: 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 = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(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 = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(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, IERC20Uniswap(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 = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(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,) = UniswapV2Library.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 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.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 = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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 = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.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, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.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, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.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,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.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 = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.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, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: 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, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: 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 UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import '../interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap 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');
}
// 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'0806007449eb32dca887e3fdc15b99d4359dd5f90e1caf06dcff2add2bdc36aa' // 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,) = 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(990); // change fee swap from 0.3% -> 1%
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(990); // change fee swap from 0.3% -> 1%
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; 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);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
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');
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, 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');
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IERC20Uniswap {
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);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
contract UniswapV2Pair is UniswapV2ERC20 {
using SafeMathUniswap for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(25).add(rootKLast); // change fee transfer to maker from 0.05% to 0.25%
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
address migrator = IUniswapV2Factory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
} else {
require(migrator == address(0), "Must not have migrator");
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(10)); // change fee swap from 0.3% -> 1%
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(10)); // change fee swap from 0.3% -> 1%
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 {
using SafeMathUniswap for uint;
string public constant name = 'TanosiaSwap LP Token';
string public constant symbol = 'TLP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
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);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// 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;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../uniswapv2/UniswapV2Pair.sol";
contract SushiSwapPairMock is UniswapV2Pair {
constructor() public UniswapV2Pair() {}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract TanosiaFactory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function pairCodeHash() external pure returns (bytes32) {
return keccak256(type(UniswapV2Pair).creationCode);
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setMigrator(address _migrator) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
migrator = _migrator;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../uniswapv2/TanosiaFactory.sol";
contract SushiSwapFactoryMock is TanosiaFactory {
constructor(address _feeToSetter) public TanosiaFactory(_feeToSetter) {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../TanosiaMaker.sol";
contract TanosiaMakerExploitMock {
TanosiaMaker public immutable tanosiaMaker;
constructor (address _tanosiaMaker) public{
tanosiaMaker = TanosiaMaker(_tanosiaMaker);
}
function convert(address token0, address token1) external {
tanosiaMaker.convert(token0, token1);
}
} | this low-level function should be called from a contract which performs important safety checks | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
| 532,165 |
/**
*Submitted for verification at Etherscan.io on 2021-10-26
*/
// 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: AggregatorInterface
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// Part: DssAutoLine
interface DssAutoLine {
function exec(bytes32 _ilk) external returns (uint256);
}
// Part: GemLike
interface GemLike {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
}
// Part: IBaseFee
interface IBaseFee {
function basefee_global() external view returns (uint256);
}
// Part: IOSMedianizer
interface IOSMedianizer {
function foresight() external view returns (uint256 price, bool osm);
function read() external view returns (uint256 price, bool osm);
}
// Part: ISwap
interface ISwap {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
// Part: JugLike
interface JugLike {
function drip(bytes32) external returns (uint256);
}
// Part: ManagerLike
interface ManagerLike {
function cdpCan(
address,
uint256,
address
) external view returns (uint256);
function ilks(uint256) external view returns (bytes32);
function owns(uint256) external view returns (address);
function urns(uint256) external view returns (address);
function vat() external view returns (address);
function open(bytes32, address) external returns (uint256);
function give(uint256, address) external;
function cdpAllow(
uint256,
address,
uint256
) external;
function urnAllow(address, uint256) external;
function frob(
uint256,
int256,
int256
) external;
function flux(
uint256,
address,
uint256
) external;
function move(
uint256,
address,
uint256
) external;
function exit(
address,
uint256,
address,
uint256
) external;
function quit(uint256, address) external;
function enter(address, uint256) external;
function shift(uint256, uint256) 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]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[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: SpotLike
interface SpotLike {
function live() external view returns (uint256);
function par() external view returns (uint256);
function vat() external view returns (address);
function ilks(bytes32) external view returns (address, uint256);
}
// Part: VatLike
interface VatLike {
function can(address, address) external view returns (uint256);
function ilks(bytes32)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function dai(address) external view returns (uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) external;
function hope(address) external;
function move(
address,
address,
uint256
) external;
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: DaiJoinLike
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
// Part: GemJoinLike
interface GemJoinLike {
function dec() external returns (uint256);
function gem() external returns (GemLike);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
// Part: IVault
interface IVault is IERC20 {
function token() external view returns (address);
function decimals() external view returns (uint256);
function deposit() external;
function pricePerShare() external view returns (uint256);
function withdraw() external returns (uint256);
function withdraw(uint256 amount) external returns (uint256);
function withdraw(
uint256 amount,
address account,
uint256 maxLoss
) external returns (uint256);
function availableDepositLimit() external view returns (uint256);
}
// 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: yearn/[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: MakerDaiDelegateLib
library MakerDaiDelegateLib {
using SafeMath for uint256;
// Units used in Maker contracts
uint256 internal constant WAD = 10**18;
uint256 internal constant RAY = 10**27;
// Do not attempt to mint DAI if there are less than MIN_MINTABLE available
uint256 internal constant MIN_MINTABLE = 500000 * WAD;
// Maker vaults manager
ManagerLike internal constant manager =
ManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// Token Adapter Module for collateral
DaiJoinLike internal constant daiJoin =
DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
// Liaison between oracles and core Maker contracts
SpotLike internal constant spotter =
SpotLike(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
// Part of the Maker Rates Module in charge of accumulating stability fees
JugLike internal constant jug =
JugLike(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
// Debt Ceiling Instant Access Module
DssAutoLine internal constant autoLine =
DssAutoLine(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3);
// ----------------- PUBLIC FUNCTIONS -----------------
// Creates an UrnHandler (cdp) for a specific ilk and allows to manage it via the internal
// registry of the manager.
function openCdp(bytes32 ilk) public returns (uint256) {
return manager.open(ilk, address(this));
}
// Moves cdpId collateral balance and debt to newCdpId.
function shiftCdp(uint256 cdpId, uint256 newCdpId) public {
manager.shift(cdpId, newCdpId);
}
// Transfers the ownership of cdp to recipient address in the manager registry.
function transferCdp(uint256 cdpId, address recipient) public {
manager.give(cdpId, recipient);
}
// Allow/revoke manager access to a cdp
function allowManagingCdp(
uint256 cdpId,
address user,
bool isAccessGranted
) public {
manager.cdpAllow(cdpId, user, isAccessGranted ? 1 : 0);
}
// Deposits collateral (gem) and mints DAI
// Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L639
function lockGemAndDraw(
address gemJoin,
uint256 cdpId,
uint256 collateralAmount,
uint256 daiToMint,
uint256 totalDebt
) public {
address urn = manager.urns(cdpId);
VatLike vat = VatLike(manager.vat());
bytes32 ilk = manager.ilks(cdpId);
if (daiToMint > 0) {
daiToMint = _forceMintWithinLimits(vat, ilk, daiToMint, totalDebt);
}
// Takes token amount from the strategy and joins into the vat
if (collateralAmount > 0) {
GemJoinLike(gemJoin).join(urn, collateralAmount);
}
// Locks token amount into the CDP and generates debt
manager.frob(
cdpId,
int256(convertTo18(gemJoin, collateralAmount)),
_getDrawDart(vat, urn, ilk, daiToMint)
);
// Moves the DAI amount to the strategy. Need to convert dai from [wad] to [rad]
manager.move(cdpId, address(this), daiToMint.mul(1e27));
// Allow access to DAI balance in the vat
vat.hope(address(daiJoin));
// Exits DAI to the user's wallet as a token
daiJoin.exit(address(this), daiToMint);
}
// Returns DAI to decrease debt and attempts to unlock any amount of collateral
// Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L758
function wipeAndFreeGem(
address gemJoin,
uint256 cdpId,
uint256 collateralAmount,
uint256 daiToRepay
) public {
address urn = manager.urns(cdpId);
// Joins DAI amount into the vat
if (daiToRepay > 0) {
daiJoin.join(urn, daiToRepay);
}
uint256 wadC = convertTo18(gemJoin, collateralAmount);
// Paybacks debt to the CDP and unlocks token amount from it
manager.frob(
cdpId,
-int256(wadC),
_getWipeDart(
VatLike(manager.vat()),
VatLike(manager.vat()).dai(urn),
urn,
manager.ilks(cdpId)
)
);
// Moves the amount from the CDP urn to proxy's address
manager.flux(cdpId, address(this), collateralAmount);
// Exits token amount to the strategy as a token
GemJoinLike(gemJoin).exit(address(this), collateralAmount);
}
function debtFloor(bytes32 ilk) public view returns (uint256) {
// uint256 Art; // Total Normalised Debt [wad]
// uint256 rate; // Accumulated Rates [ray]
// uint256 spot; // Price with Safety Margin [ray]
// uint256 line; // Debt Ceiling [rad]
// uint256 dust; // Urn Debt Floor [rad]
(, , , , uint256 dust) = VatLike(manager.vat()).ilks(ilk);
return dust.div(RAY);
}
function debtForCdp(uint256 cdpId, bytes32 ilk)
public
view
returns (uint256)
{
address urn = manager.urns(cdpId);
VatLike vat = VatLike(manager.vat());
// Normalized outstanding stablecoin debt [wad]
(, uint256 art) = vat.urns(ilk, urn);
// Gets actual rate from the vat [ray]
(, uint256 rate, , , ) = vat.ilks(ilk);
// Return the present value of the debt with accrued fees
return art.mul(rate).div(RAY);
}
function balanceOfCdp(uint256 cdpId, bytes32 ilk)
public
view
returns (uint256)
{
address urn = manager.urns(cdpId);
VatLike vat = VatLike(manager.vat());
(uint256 ink, ) = vat.urns(ilk, urn);
return ink;
}
// Returns value of DAI in the reference asset (e.g. $1 per DAI)
function getDaiPar() public view returns (uint256) {
// Value is returned in ray (10**27)
return spotter.par();
}
// Liquidation ratio for the given ilk returned in [ray]
// https://github.com/makerdao/dss/blob/master/src/spot.sol#L45
function getLiquidationRatio(bytes32 ilk) public view returns (uint256) {
(, uint256 liquidationRatio) = spotter.ilks(ilk);
return liquidationRatio;
}
function getSpotPrice(bytes32 ilk) public view returns (uint256) {
VatLike vat = VatLike(manager.vat());
// spot: collateral price with safety margin returned in [ray]
(, , uint256 spot, , ) = vat.ilks(ilk);
uint256 liquidationRatio = getLiquidationRatio(ilk);
// convert ray*ray to wad
return spot.mul(liquidationRatio).div(RAY * 1e9);
}
function getPessimisticRatioOfCdpWithExternalPrice(
uint256 cdpId,
bytes32 ilk,
uint256 externalPrice,
uint256 collateralizationRatioPrecision
) public view returns (uint256) {
// Use pessimistic price to determine the worst ratio possible
uint256 price = Math.min(getSpotPrice(ilk), externalPrice);
require(price > 0); // dev: invalid price
uint256 totalCollateralValue =
balanceOfCdp(cdpId, ilk).mul(price).div(WAD);
uint256 totalDebt = debtForCdp(cdpId, ilk);
// If for some reason we do not have debt (e.g: deposits under dust)
// make sure the operation does not revert
if (totalDebt == 0) {
totalDebt = 1;
}
return
totalCollateralValue.mul(collateralizationRatioPrecision).div(
totalDebt
);
}
// Make sure we update some key content in Maker contracts
// These can be updated by anyone without authenticating
function keepBasicMakerHygiene(bytes32 ilk) public {
// Update accumulated stability fees
jug.drip(ilk);
// Update the debt ceiling using DSS Auto Line
autoLine.exec(ilk);
}
function daiJoinAddress() public view returns (address) {
return address(daiJoin);
}
// Checks if there is at least MIN_MINTABLE dai available to be minted
function isDaiAvailableToMint(bytes32 ilk) public view returns (bool) {
VatLike vat = VatLike(manager.vat());
(uint256 Art, uint256 rate, , uint256 line, ) = vat.ilks(ilk);
// Total debt in [rad] (wad * ray)
uint256 vatDebt = Art.mul(rate);
if (vatDebt >= line || line.sub(vatDebt).div(RAY) < MIN_MINTABLE) {
return false;
}
return true;
}
// ----------------- INTERNAL FUNCTIONS -----------------
// This function repeats some code from daiAvailableToMint because it needs
// to handle special cases such as not leaving debt under dust
function _forceMintWithinLimits(
VatLike vat,
bytes32 ilk,
uint256 desiredAmount,
uint256 debtBalance
) internal view returns (uint256) {
// uint256 Art; // Total Normalised Debt [wad]
// uint256 rate; // Accumulated Rates [ray]
// uint256 spot; // Price with Safety Margin [ray]
// uint256 line; // Debt Ceiling [rad]
// uint256 dust; // Urn Debt Floor [rad]
(uint256 Art, uint256 rate, , uint256 line, uint256 dust) =
vat.ilks(ilk);
// Total debt in [rad] (wad * ray)
uint256 vatDebt = Art.mul(rate);
// Make sure we are not over debt ceiling (line) or under debt floor (dust)
if (
vatDebt >= line || (desiredAmount.add(debtBalance) <= dust.div(RAY))
) {
return 0;
}
uint256 maxMintableDAI = line.sub(vatDebt).div(RAY);
// Avoid edge cases with low amounts of available debt
if (maxMintableDAI < MIN_MINTABLE) {
return 0;
}
// Prevent rounding errors
if (maxMintableDAI > WAD) {
maxMintableDAI = maxMintableDAI - WAD;
}
return Math.min(maxMintableDAI, desiredAmount);
}
// Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L161
function _getDrawDart(
VatLike vat,
address urn,
bytes32 ilk,
uint256 wad
) internal returns (int256 dart) {
// Updates stability fee rate
uint256 rate = jug.drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = vat.dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < wad.mul(RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = int256(wad.mul(RAY).sub(dai).div(rate));
// This is neeeded due to lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart;
}
}
// Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L183
function _getWipeDart(
VatLike vat,
uint256 dai,
address urn,
bytes32 ilk
) internal view returns (int256 dart) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = vat.ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = vat.urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = int256(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -int256(art);
}
function convertTo18(address gemJoin, uint256 amt)
internal
returns (uint256 wad)
{
// For those collaterals that have less than 18 decimals precision we need to do the conversion before
// passing to frob function
// Adapters will automatically handle the difference of precision
wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec()));
}
}
// Part: yearn/[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;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @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.4.3";
}
/**
* @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 view virtual 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 view virtual 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 onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!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"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!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.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a 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
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @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 conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @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 view virtual 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`).
*
* `_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.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @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
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual 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.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
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
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* 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/main/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 callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
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 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} 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.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
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 the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
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 onlyEmergencyAuthorized {
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 view virtual 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)));
}
}
// Part: Strategy
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Units used in Maker contracts
uint256 internal constant WAD = 10**18;
uint256 internal constant RAY = 10**27;
// DAI token
IERC20 internal constant investmentToken =
IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
// 100%
uint256 internal constant MAX_BPS = WAD;
// Maximum loss on withdrawal from yVault
uint256 internal constant MAX_LOSS_BPS = 10000;
// Wrapped Ether - Used for swaps routing
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// SushiSwap router
ISwap internal constant sushiswapRouter =
ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
// Uniswap router
ISwap internal constant uniswapRouter =
ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Provider to read current block's base fee
IBaseFee internal constant baseFeeProvider =
IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549);
// Token Adapter Module for collateral
address public gemJoinAdapter;
// Maker Oracle Security Module
IOSMedianizer public wantToUSDOSMProxy;
// Use Chainlink oracle to obtain latest want/ETH price
AggregatorInterface public chainlinkWantToETHPriceFeed;
// DAI yVault
IVault public yVault;
// Router used for swaps
ISwap public router;
// Collateral type
bytes32 public ilk;
// Our vault identifier
uint256 public cdpId;
// Our desired collaterization ratio
uint256 public collateralizationRatio;
// Allow the collateralization ratio to drift a bit in order to avoid cycles
uint256 public rebalanceTolerance;
// Max acceptable base fee to take more debt or harvest
uint256 public maxAcceptableBaseFee;
// Maximum acceptable loss on withdrawal. Default to 0.01%.
uint256 public maxLoss;
// If set to true the strategy will never try to repay debt by selling want
bool public leaveDebtBehind;
// Name of the strategy
string internal strategyName;
// ----------------- INIT FUNCTIONS TO SUPPORT CLONING -----------------
constructor(
address _vault,
address _yVault,
string memory _strategyName,
bytes32 _ilk,
address _gemJoin,
address _wantToUSDOSMProxy,
address _chainlinkWantToETHPriceFeed
) public BaseStrategy(_vault) {
_initializeThis(
_yVault,
_strategyName,
_ilk,
_gemJoin,
_wantToUSDOSMProxy,
_chainlinkWantToETHPriceFeed
);
}
function initialize(
address _vault,
address _yVault,
string memory _strategyName,
bytes32 _ilk,
address _gemJoin,
address _wantToUSDOSMProxy,
address _chainlinkWantToETHPriceFeed
) public {
// Make sure we only initialize one time
require(address(yVault) == address(0)); // dev: strategy already initialized
address sender = msg.sender;
// Initialize BaseStrategy
_initialize(_vault, sender, sender, sender);
// Initialize cloned instance
_initializeThis(
_yVault,
_strategyName,
_ilk,
_gemJoin,
_wantToUSDOSMProxy,
_chainlinkWantToETHPriceFeed
);
}
function _initializeThis(
address _yVault,
string memory _strategyName,
bytes32 _ilk,
address _gemJoin,
address _wantToUSDOSMProxy,
address _chainlinkWantToETHPriceFeed
) internal {
yVault = IVault(_yVault);
strategyName = _strategyName;
ilk = _ilk;
gemJoinAdapter = _gemJoin;
wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy);
chainlinkWantToETHPriceFeed = AggregatorInterface(
_chainlinkWantToETHPriceFeed
);
// Set default router to SushiSwap
router = sushiswapRouter;
// Set health check to health.ychad.eth
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012;
cdpId = MakerDaiDelegateLib.openCdp(ilk);
require(cdpId > 0); // dev: error opening cdp
// Current ratio can drift (collateralizationRatio - rebalanceTolerance, collateralizationRatio + rebalanceTolerance)
// Allow additional 15% in any direction (210, 240) by default
rebalanceTolerance = (15 * MAX_BPS) / 100;
// Minimum collaterization ratio on YFI-A is 175%
// Use 225% as target
collateralizationRatio = (225 * MAX_BPS) / 100;
// If we lose money in yvDAI then we are not OK selling want to repay it
leaveDebtBehind = true;
// Define maximum acceptable loss on withdrawal to be 0.01%.
maxLoss = 1;
// Set max acceptable base fee to take on more debt to 60 gwei
maxAcceptableBaseFee = 60 * 1e9;
}
// ----------------- SETTERS & MIGRATION -----------------
// Maximum acceptable base fee of current block to take on more debt
function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee)
external
onlyEmergencyAuthorized
{
maxAcceptableBaseFee = _maxAcceptableBaseFee;
}
// Target collateralization ratio to maintain within bounds
function setCollateralizationRatio(uint256 _collateralizationRatio)
external
onlyEmergencyAuthorized
{
require(
_collateralizationRatio.sub(rebalanceTolerance) >
MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div(
RAY
)
); // dev: desired collateralization ratio is too low
collateralizationRatio = _collateralizationRatio;
}
// Rebalancing bands (collat ratio - tolerance, collat_ratio + tolerance)
function setRebalanceTolerance(uint256 _rebalanceTolerance)
external
onlyEmergencyAuthorized
{
require(
collateralizationRatio.sub(_rebalanceTolerance) >
MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div(
RAY
)
); // dev: desired rebalance tolerance makes allowed ratio too low
rebalanceTolerance = _rebalanceTolerance;
}
// Max slippage to accept when withdrawing from yVault
function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers {
require(_maxLoss <= MAX_LOSS_BPS); // dev: invalid value for max loss
maxLoss = _maxLoss;
}
// If set to true the strategy will never sell want to repay debts
function setLeaveDebtBehind(bool _leaveDebtBehind)
external
onlyEmergencyAuthorized
{
leaveDebtBehind = _leaveDebtBehind;
}
// Required to move funds to a new cdp and use a different cdpId after migration
// Should only be called by governance as it will move funds
function shiftToCdp(uint256 newCdpId) external onlyGovernance {
MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId);
cdpId = newCdpId;
}
// Move yvDAI funds to a new yVault
function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance {
uint256 balanceOfYVault = yVault.balanceOf(address(this));
if (balanceOfYVault > 0) {
yVault.withdraw(balanceOfYVault, address(this), maxLoss);
}
investmentToken.safeApprove(address(yVault), 0);
yVault = newYVault;
_depositInvestmentTokenInYVault();
}
// Allow address to manage Maker's CDP
function grantCdpManagingRightsToUser(address user, bool allow)
external
onlyGovernance
{
MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow);
}
// Allow switching between Uniswap and SushiSwap
function switchDex(bool isUniswap) external onlyVaultManagers {
if (isUniswap) {
router = uniswapRouter;
} else {
router = sushiswapRouter;
}
}
// Allow external debt repayment
// Attempt to take currentRatio to target c-ratio
// Passing zero will repay all debt if possible
function emergencyDebtRepayment(uint256 currentRatio)
external
onlyVaultManagers
{
_repayDebt(currentRatio);
}
// Allow repayment of an arbitrary amount of Dai without having to
// grant access to the CDP in case of an emergency
// Difference with `emergencyDebtRepayment` function above is that here we
// are short-circuiting all strategy logic and repaying Dai at once
// This could be helpful if for example yvDAI withdrawals are failing and
// we want to do a Dai airdrop and direct debt repayment instead
function repayDebtWithDaiBalance(uint256 amount)
external
onlyVaultManagers
{
_repayInvestmentTokenDebt(amount);
}
// ******** OVERRIDEN METHODS FROM BASE CONTRACT ************
function name() external view override returns (string memory) {
return strategyName;
}
function delegatedAssets() external view override returns (uint256) {
return _convertInvestmentTokenToWant(_valueOfInvestment());
}
function estimatedTotalAssets() public view override returns (uint256) {
return
balanceOfWant()
.add(balanceOfMakerVault())
.add(_convertInvestmentTokenToWant(balanceOfInvestmentToken()))
.add(_convertInvestmentTokenToWant(_valueOfInvestment()))
.sub(_convertInvestmentTokenToWant(balanceOfDebt()));
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
// Claim rewards from yVault
_takeYVaultProfit();
uint256 totalAssetsAfterProfit = estimatedTotalAssets();
_profit = totalAssetsAfterProfit > totalDebt
? totalAssetsAfterProfit.sub(totalDebt)
: 0;
uint256 _amountFreed;
(_amountFreed, _loss) = liquidatePosition(
_debtOutstanding.add(_profit)
);
_debtPayment = Math.min(_debtOutstanding, _amountFreed);
if (_loss > _profit) {
// Example:
// debtOutstanding 100, profit 50, _amountFreed 100, _loss 50
// loss should be 0, (50-50)
// profit should endup in 0
_loss = _loss.sub(_profit);
_profit = 0;
} else {
// Example:
// debtOutstanding 100, profit 50, _amountFreed 140, _loss 10
// _profit should be 40, (50 profit - 10 loss)
// loss should end up in be 0
_profit = _profit.sub(_loss);
_loss = 0;
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
MakerDaiDelegateLib.keepBasicMakerHygiene(ilk);
// If we have enough want to deposit more into the maker vault, we do it
// Do not skip the rest of the function as it may need to repay or take on more debt
uint256 wantBalance = balanceOfWant();
if (wantBalance > _debtOutstanding) {
uint256 amountToDeposit = wantBalance.sub(_debtOutstanding);
_depositToMakerVault(amountToDeposit);
}
// Allow the ratio to move a bit in either direction to avoid cycles
uint256 currentRatio = getCurrentMakerVaultRatio();
if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) {
_repayDebt(currentRatio);
} else if (
currentRatio > collateralizationRatio.add(rebalanceTolerance)
) {
_mintMoreInvestmentToken();
}
// If we have anything left to invest then deposit into the yVault
_depositInvestmentTokenInYVault();
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 balance = balanceOfWant();
// Check if we can handle it without freeing collateral
if (balance >= _amountNeeded) {
return (_amountNeeded, 0);
}
// We only need to free the amount of want not readily available
uint256 amountToFree = _amountNeeded.sub(balance);
uint256 price = _getWantTokenPrice();
uint256 collateralBalance = balanceOfMakerVault();
// We cannot free more than what we have locked
amountToFree = Math.min(amountToFree, collateralBalance);
uint256 totalDebt = balanceOfDebt();
// If for some reason we do not have debt, make sure the operation does not revert
if (totalDebt == 0) {
totalDebt = 1;
}
uint256 toFreeIT = amountToFree.mul(price).div(WAD);
uint256 collateralIT = collateralBalance.mul(price).div(WAD);
uint256 newRatio =
collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt);
// Attempt to repay necessary debt to restore the target collateralization ratio
_repayDebt(newRatio);
// Unlock as much collateral as possible while keeping the target ratio
amountToFree = Math.min(amountToFree, _maxWithdrawal());
_freeCollateralAndRepayDai(amountToFree, 0);
// If we still need more want to repay, we may need to unlock some collateral to sell
if (
!leaveDebtBehind &&
balanceOfWant() < _amountNeeded &&
balanceOfDebt() > 0
) {
_sellCollateralToRepayRemainingDebtIfNeeded();
}
uint256 looseWant = balanceOfWant();
if (_amountNeeded > looseWant) {
_liquidatedAmount = looseWant;
_loss = _amountNeeded.sub(looseWant);
} else {
_liquidatedAmount = _amountNeeded;
_loss = 0;
}
}
function liquidateAllPositions()
internal
override
returns (uint256 _amountFreed)
{
(_amountFreed, ) = liquidatePosition(estimatedTotalAssets());
}
function harvestTrigger(uint256 callCost)
public
view
override
returns (bool)
{
return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost);
}
function tendTrigger(uint256 callCostInWei)
public
view
override
returns (bool)
{
// Nothing to adjust if there is no collateral locked
if (balanceOfMakerVault() == 0) {
return false;
}
uint256 currentRatio = getCurrentMakerVaultRatio();
// If we need to repay debt and are outside the tolerance bands,
// we do it regardless of the call cost
if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) {
return true;
}
// Mint more DAI if possible
return
currentRatio > collateralizationRatio.add(rebalanceTolerance) &&
balanceOfDebt() > 0 &&
isCurrentBaseFeeAcceptable() &&
MakerDaiDelegateLib.isDaiAvailableToMint(ilk);
}
function prepareMigration(address _newStrategy) internal override {
// Transfer Maker Vault ownership to the new startegy
MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy);
// Move yvDAI balance to the new strategy
IERC20(yVault).safeTransfer(
_newStrategy,
yVault.balanceOf(address(this))
);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
function ethToWant(uint256 _amtInWei)
public
view
virtual
override
returns (uint256)
{
if (address(want) == address(WETH)) {
return _amtInWei;
}
uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer());
return _amtInWei.mul(WAD).div(price);
}
// ----------------- INTERNAL FUNCTIONS SUPPORT -----------------
function _repayDebt(uint256 currentRatio) internal {
uint256 currentDebt = balanceOfDebt();
// Nothing to repay if we are over the collateralization ratio
// or there is no debt
if (currentRatio > collateralizationRatio || currentDebt == 0) {
return;
}
// ratio = collateral / debt
// collateral = current_ratio * current_debt
// collateral amount is invariant here so we want to find new_debt
// so that new_debt * desired_ratio = current_debt * current_ratio
// new_debt = current_debt * current_ratio / desired_ratio
// and the amount to repay is the difference between current_debt and new_debt
uint256 newDebt =
currentDebt.mul(currentRatio).div(collateralizationRatio);
uint256 amountToRepay;
// Maker will revert if the outstanding debt is less than a debt floor
// called 'dust'. If we are there we need to either pay the debt in full
// or leave at least 'dust' balance (10,000 DAI for YFI-A)
uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk);
if (newDebt <= debtFloor) {
// If we sold want to repay debt we will have DAI readily available in the strategy
// This means we need to count both yvDAI shares and current DAI balance
uint256 totalInvestmentAvailableToRepay =
_valueOfInvestment().add(balanceOfInvestmentToken());
if (totalInvestmentAvailableToRepay >= currentDebt) {
// Pay the entire debt if we have enough investment token
amountToRepay = currentDebt;
} else {
// Pay just 0.1 cent above debtFloor (best effort without liquidating want)
amountToRepay = currentDebt.sub(debtFloor).sub(1e15);
}
} else {
// If we are not near the debt floor then just pay the exact amount
// needed to obtain a healthy collateralization ratio
amountToRepay = currentDebt.sub(newDebt);
}
uint256 balanceIT = balanceOfInvestmentToken();
if (amountToRepay > balanceIT) {
_withdrawFromYVault(amountToRepay.sub(balanceIT));
}
_repayInvestmentTokenDebt(amountToRepay);
}
function _sellCollateralToRepayRemainingDebtIfNeeded() internal {
uint256 currentInvestmentValue = _valueOfInvestment();
uint256 investmentLeftToAcquire =
balanceOfDebt().sub(currentInvestmentValue);
uint256 investmentLeftToAcquireInWant =
_convertInvestmentTokenToWant(investmentLeftToAcquire);
if (investmentLeftToAcquireInWant <= balanceOfWant()) {
_buyInvestmentTokenWithWant(investmentLeftToAcquire);
_repayDebt(0);
_freeCollateralAndRepayDai(balanceOfMakerVault(), 0);
}
}
// Mint the maximum DAI possible for the locked collateral
function _mintMoreInvestmentToken() internal {
uint256 price = _getWantTokenPrice();
uint256 amount = balanceOfMakerVault();
uint256 daiToMint =
amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD);
daiToMint = daiToMint.sub(balanceOfDebt());
_lockCollateralAndMintDai(0, daiToMint);
}
function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) {
if (_amountIT == 0) {
return 0;
}
// No need to check allowance because the contract == token
uint256 balancePrior = balanceOfInvestmentToken();
uint256 sharesToWithdraw =
Math.min(
_investmentTokenToYShares(_amountIT),
yVault.balanceOf(address(this))
);
if (sharesToWithdraw == 0) {
return 0;
}
yVault.withdraw(sharesToWithdraw, address(this), maxLoss);
return balanceOfInvestmentToken().sub(balancePrior);
}
function _depositInvestmentTokenInYVault() internal {
uint256 balanceIT = balanceOfInvestmentToken();
if (balanceIT > 0) {
_checkAllowance(
address(yVault),
address(investmentToken),
balanceIT
);
yVault.deposit();
}
}
function _repayInvestmentTokenDebt(uint256 amount) internal {
if (amount == 0) {
return;
}
uint256 debt = balanceOfDebt();
uint256 balanceIT = balanceOfInvestmentToken();
// We cannot pay more than loose balance
amount = Math.min(amount, balanceIT);
// We cannot pay more than we owe
amount = Math.min(amount, debt);
_checkAllowance(
MakerDaiDelegateLib.daiJoinAddress(),
address(investmentToken),
amount
);
if (amount > 0) {
// When repaying the full debt it is very common to experience Vat/dust
// reverts due to the debt being non-zero and less than the debt floor.
// This can happen due to rounding when _wipeAndFreeGem() divides
// the DAI amount by the accumulated stability fee rate.
// To circumvent this issue we will add 1 Wei to the amount to be paid
// if there is enough investment token balance (DAI) to do it.
if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) {
amount = amount.add(1);
}
// Repay debt amount without unlocking collateral
_freeCollateralAndRepayDai(0, amount);
}
}
function _checkAllowance(
address _contract,
address _token,
uint256 _amount
) internal {
if (IERC20(_token).allowance(address(this), _contract) < _amount) {
IERC20(_token).safeApprove(_contract, 0);
IERC20(_token).safeApprove(_contract, type(uint256).max);
}
}
function _takeYVaultProfit() internal {
uint256 _debt = balanceOfDebt();
uint256 _valueInVault = _valueOfInvestment();
if (_debt >= _valueInVault) {
return;
}
uint256 profit = _valueInVault.sub(_debt);
uint256 ySharesToWithdraw = _investmentTokenToYShares(profit);
if (ySharesToWithdraw > 0) {
yVault.withdraw(ySharesToWithdraw, address(this), maxLoss);
_sellAForB(
balanceOfInvestmentToken(),
address(investmentToken),
address(want)
);
}
}
function _depositToMakerVault(uint256 amount) internal {
if (amount == 0) {
return;
}
_checkAllowance(gemJoinAdapter, address(want), amount);
uint256 price = _getWantTokenPrice();
uint256 daiToMint =
amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD);
_lockCollateralAndMintDai(amount, daiToMint);
}
// Returns maximum collateral to withdraw while maintaining the target collateralization ratio
function _maxWithdrawal() internal view returns (uint256) {
// Denominated in want
uint256 totalCollateral = balanceOfMakerVault();
// Denominated in investment token
uint256 totalDebt = balanceOfDebt();
// If there is no debt to repay we can withdraw all the locked collateral
if (totalDebt == 0) {
return totalCollateral;
}
uint256 price = _getWantTokenPrice();
// Min collateral in want that needs to be locked with the outstanding debt
// Allow going to the lower rebalancing band
uint256 minCollateral =
collateralizationRatio
.sub(rebalanceTolerance)
.mul(totalDebt)
.mul(WAD)
.div(price)
.div(MAX_BPS);
// If we are under collateralized then it is not safe for us to withdraw anything
if (minCollateral > totalCollateral) {
return 0;
}
return totalCollateral.sub(minCollateral);
}
// ----------------- PUBLIC BALANCES AND CALCS -----------------
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function balanceOfInvestmentToken() public view returns (uint256) {
return investmentToken.balanceOf(address(this));
}
function balanceOfDebt() public view returns (uint256) {
return MakerDaiDelegateLib.debtForCdp(cdpId, ilk);
}
// Returns collateral balance in the vault
function balanceOfMakerVault() public view returns (uint256) {
return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk);
}
// Effective collateralization ratio of the vault
function getCurrentMakerVaultRatio() public view returns (uint256) {
return
MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice(
cdpId,
ilk,
_getWantTokenPrice(),
MAX_BPS
);
}
// Check if current block's base fee is under max allowed base fee
function isCurrentBaseFeeAcceptable() public view returns (bool) {
uint256 baseFee;
try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {
baseFee = currentBaseFee;
} catch {
// Useful for testing until ganache supports london fork
// Hard-code current base fee to 1000 gwei
// This should also help keepers that run in a fork without
// baseFee() to avoid reverting and potentially abandoning the job
baseFee = 1000 * 1e9;
}
return baseFee <= maxAcceptableBaseFee;
}
// ----------------- INTERNAL CALCS -----------------
// Returns the minimum price available
function _getWantTokenPrice() internal view returns (uint256) {
// Use price from spotter as base
uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk);
// Peek the OSM to get current price
try wantToUSDOSMProxy.read() returns (
uint256 current,
bool currentIsValid
) {
if (currentIsValid && current > 0) {
minPrice = Math.min(minPrice, current);
}
} catch {
// Ignore price peek()'d from OSM. Maybe we are no longer authorized.
}
// Peep the OSM to get future price
try wantToUSDOSMProxy.foresight() returns (
uint256 future,
bool futureIsValid
) {
if (futureIsValid && future > 0) {
minPrice = Math.min(minPrice, future);
}
} catch {
// Ignore price peep()'d from OSM. Maybe we are no longer authorized.
}
// If price is set to 0 then we hope no liquidations are taking place
// Emergency scenarios can be handled via manual debt repayment or by
// granting governance access to the CDP
require(minPrice > 0); // dev: invalid spot price
// par is crucial to this calculation as it defines the relationship between DAI and
// 1 unit of value in the price
return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar());
}
function _valueOfInvestment() internal view returns (uint256) {
return
yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div(
10**yVault.decimals()
);
}
function _investmentTokenToYShares(uint256 amount)
internal
view
returns (uint256)
{
return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare());
}
function _lockCollateralAndMintDai(
uint256 collateralAmount,
uint256 daiToMint
) internal {
MakerDaiDelegateLib.lockGemAndDraw(
gemJoinAdapter,
cdpId,
collateralAmount,
daiToMint,
balanceOfDebt()
);
}
function _freeCollateralAndRepayDai(
uint256 collateralAmount,
uint256 daiToRepay
) internal {
MakerDaiDelegateLib.wipeAndFreeGem(
gemJoinAdapter,
cdpId,
collateralAmount,
daiToRepay
);
}
// ----------------- TOKEN CONVERSIONS -----------------
function _convertInvestmentTokenToWant(uint256 amount)
internal
view
returns (uint256)
{
return amount.mul(WAD).div(_getWantTokenPrice());
}
function _getTokenOutPath(address _token_in, address _token_out)
internal
pure
returns (address[] memory _path)
{
bool is_weth =
_token_in == address(WETH) || _token_out == address(WETH);
_path = new address[](is_weth ? 2 : 3);
_path[0] = _token_in;
if (is_weth) {
_path[1] = _token_out;
} else {
_path[1] = address(WETH);
_path[2] = _token_out;
}
}
function _sellAForB(
uint256 _amount,
address tokenA,
address tokenB
) internal {
if (_amount == 0 || tokenA == tokenB) {
return;
}
_checkAllowance(address(router), tokenA, _amount);
router.swapExactTokensForTokens(
_amount,
0,
_getTokenOutPath(tokenA, tokenB),
address(this),
now
);
}
function _buyInvestmentTokenWithWant(uint256 _amount) internal {
if (_amount == 0 || address(investmentToken) == address(want)) {
return;
}
_checkAllowance(address(router), address(want), _amount);
router.swapTokensForExactTokens(
_amount,
type(uint256).max,
_getTokenOutPath(address(want), address(investmentToken)),
address(this),
now
);
}
}
// File: MakerDaiDelegateCloner.sol
contract MakerDaiDelegateCloner {
address public immutable original;
event Cloned(address indexed clone);
event Deployed(address indexed original);
constructor(
address _vault,
address _yVault,
string memory _strategyName,
bytes32 _ilk,
address _gemJoin,
address _wantToUSDOSMProxy,
address _chainlinkWantToETHPriceFeed
) public {
Strategy _original =
new Strategy(
_vault,
_yVault,
_strategyName,
_ilk,
_gemJoin,
_wantToUSDOSMProxy,
_chainlinkWantToETHPriceFeed
);
emit Deployed(address(_original));
original = address(_original);
Strategy(_original).setRewards(
0xc491599b9A20c3A2F0A85697Ee6D9434EFa9f503
);
Strategy(_original).setKeeper(
0x736D7e3c5a6CB2CE3B764300140ABF476F6CFCCF
);
Strategy(_original).setStrategist(
0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7
);
}
function cloneMakerDaiDelegate(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _yVault,
string memory _strategyName,
bytes32 _ilk,
address _gemJoin,
address _wantToUSDOSMProxy,
address _chainlinkWantToETHPriceFeed
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(
_vault,
_yVault,
_strategyName,
_ilk,
_gemJoin,
_wantToUSDOSMProxy,
_chainlinkWantToETHPriceFeed
);
Strategy(newStrategy).setKeeper(_keeper);
Strategy(newStrategy).setRewards(_rewards);
Strategy(newStrategy).setStrategist(_strategist);
emit Cloned(newStrategy);
}
function name() external pure returns (string memory) {
return "[email protected]";
}
} | Claim rewards from yVault Example: debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 loss should be 0, (50-50) profit should endup in 0 Example: debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 _profit should be 40, (50 profit - 10 loss) loss should end up in be 0 | function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
_takeYVaultProfit();
uint256 totalAssetsAfterProfit = estimatedTotalAssets();
_profit = totalAssetsAfterProfit > totalDebt
? totalAssetsAfterProfit.sub(totalDebt)
: 0;
uint256 _amountFreed;
(_amountFreed, _loss) = liquidatePosition(
_debtOutstanding.add(_profit)
);
_debtPayment = Math.min(_debtOutstanding, _amountFreed);
if (_loss > _profit) {
_loss = _loss.sub(_profit);
_profit = 0;
_profit = _profit.sub(_loss);
_loss = 0;
}
}
| 508,390 |
./partial_match/1/0x5D2A8C81f349D93f814acC9Aa3D3D62f54F7A19D/sources/AmbrosusSale.sol | Approve allowances Mitigate the race condition described here: https:github.com/ethereum/EIPs/issues/20issuecomment-263524729 | function approve(address _spender, uint256 _value)
when_liquid
returns (bool)
{
require (_value == 0 || accounts[msg.sender].allowanceOf[_spender] == 0);
Approval(msg.sender, _spender, _value);
accounts[msg.sender].allowanceOf[_spender] = _value;
return true;
}
| 3,930,233 |
./full_match/4/0x38985565Ad76b51F659ca6B4f5B409033720A155/sources/browser/Untitled.sol | this let the user see all their insults so far | function My_Total_Insults() public view returns (uint) {
return badWords;
}
| 12,357,655 |
./full_match/11155111/0xF551C46E14eD3cc81292Ef8A98FB393990de6518/sources/project_/contracts/interfaces/IInsurance.sol | Interface of the Insurance Policy Token./ | interface IInsurance {
event RoyaltiesSet(address indexed beneficiary, uint256 bps);
event RoyaltiesPaid(address indexed beneficiary, address indexed token, uint256 amount);
function insurer() external view returns (address);
function currency() external view returns (address);
function insuranceOwner() external view returns (address);
function isDeactivated() external view returns (bool);
function documentStorage() external view returns (bytes32);
function documentationURI() external view returns (string calldata);
function policyNumber() external view returns (string calldata);
function monthlyPremium() external view returns (uint256);
receive() external payable;
function collectMonthlyPremium() external;
function transferCoin(address to, uint256 amount) external;
function safeTransferERC20(address token, address to, uint256 amount) external;
function deactivate() external;
function setNewPolicyNumber(string calldata newPolicyNumber) external;
function setNewDocumentationURI(string calldata newDocumentationURI) external;
function setDocumentStorage(bytes32 newStorage) external;
function setProvider(address newProvider) external;
}
| 3,836,417 |
./full_match/80001/0xaE4f334860d10B1893D7E66aA60b2f6Ab1361c55/sources/project_/contracts/roles/Operators.sol | Sets a new default operator operator The address of the new default operator/ | function setDefaultOperator(address operator) public onlyOwner {
emit DefaultOperator(operator, _defaultOperator);
_defaultOperator = operator;
}
| 5,662,962 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
contract ErrorReporter {
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
*/
event Failure(uint256 error, uint256 info, uint256 detail);
enum Error {
NO_ERROR,
OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event
UNAUTHORIZED,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW,
DIVISION_BY_ZERO,
BAD_INPUT,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_TRANSFER_FAILED,
MARKET_NOT_SUPPORTED,
SUPPLY_RATE_CALCULATION_FAILED,
BORROW_RATE_CALCULATION_FAILED,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_OUT_FAILED,
INSUFFICIENT_LIQUIDITY,
INSUFFICIENT_BALANCE,
INVALID_COLLATERAL_RATIO,
MISSING_ASSET_PRICE,
EQUITY_INSUFFICIENT_BALANCE,
INVALID_CLOSE_AMOUNT_REQUESTED,
ASSET_NOT_PRICED,
INVALID_LIQUIDATION_DISCOUNT,
INVALID_COMBINED_RISK_PARAMETERS
}
/**
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
BORROW_ACCOUNT_SHORTFALL_PRESENT,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_AMOUNT_LIQUIDITY_SHORTFALL,
BORROW_AMOUNT_VALUE_CALCULATION_FAILED,
BORROW_MARKET_NOT_SUPPORTED,
BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
BORROW_ORIGINATION_FEE_CALCULATION_FAILED,
BORROW_TRANSFER_OUT_FAILED,
EQUITY_WITHDRAWAL_AMOUNT_VALIDATION,
EQUITY_WITHDRAWAL_CALCULATE_EQUITY,
EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK,
EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED,
LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED,
LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED,
LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH,
LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_TRANSFER_IN_FAILED,
LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_ADMIN_OWNER_CHECK,
SET_ASSET_PRICE_CHECK_ORACLE,
SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_ORACLE_OWNER_CHECK,
SET_ORIGINATION_FEE_OWNER_CHECK,
SET_RISK_PARAMETERS_OWNER_CHECK,
SET_RISK_PARAMETERS_VALIDATION,
SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED,
SUPPLY_MARKET_NOT_SUPPORTED,
SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
SUPPLY_TRANSFER_IN_FAILED,
SUPPLY_TRANSFER_IN_NOT_POSSIBLE,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_MARKET_PRICE_CHECK,
SUSPEND_MARKET_OWNER_CHECK,
WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
WITHDRAW_ACCOUNT_SHORTFALL_PRESENT,
WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL,
WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED,
WITHDRAW_CAPACITY_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
WITHDRAW_TRANSFER_OUT_FAILED,
WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
}
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(FailureInfo info, uint256 opaqueError)
internal
returns (uint256)
{
emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError);
return uint256(Error.OPAQUE_ERROR);
}
}
contract CarefulMath is ErrorReporter {
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (a == 0) {
return (Error.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (Error.INTEGER_OVERFLOW, 0);
} else {
return (Error.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b == 0) {
return (Error.DIVISION_BY_ZERO, 0);
}
return (Error.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b <= a) {
return (Error.NO_ERROR, a - b);
} else {
return (Error.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (Error, uint256) {
uint256 c = a + b;
if (c >= a) {
return (Error.NO_ERROR, c);
} else {
return (Error.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSub(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (Error, uint256) {
(Error err0, uint256 sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
/**
* @dev Add two numbers together, overflow will lead to revert.
*/
function srcAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
/**
* @dev Integer subtraction of two numbers, overflow will lead to revert.
*/
function srcSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
/**
* @dev Multiplies two numbers, overflow will lead to revert.
*/
function srcMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function srcDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y > 0, "ds-math-div-overflow");
z = x / y;
}
/**
* @dev x to the power of y power(base, exponent)
*/
function pow(uint256 base, uint256 exponent) internal pure returns (uint256) {
if (exponent == 0) {
return 1;
} else if (exponent == 1) {
return base;
} else if (base == 0 && exponent != 0) {
return 0;
} else {
uint256 z = base;
for (uint256 i = 1; i < exponent; i++) z = srcMul(z, base);
return z;
}
}
}
contract Exponential is CarefulMath {
// TODO: We may wish to put the result of 10**18 here instead of the expression.
// Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
// the optimizer MAY replace the expression 10**18 with its calculated value.
uint256 constant expScale = 10**18;
// See TODO on expScale
uint256 constant halfExpScale = expScale / 2;
struct Exp {
uint256 mantissa;
}
uint256 constant mantissaOne = 10**18;
uint256 constant mantissaOneTenth = 10**17;
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
(Error err1, uint256 rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({ mantissa: 0 }));
}
return (Error.NO_ERROR, Exp({ mantissa: rational }));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = add(a.mantissa, b.mantissa);
return (error, Exp({ mantissa: result }));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = sub(a.mantissa, b.mantissa);
return (error, Exp({ mantissa: result }));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return (Error.NO_ERROR, Exp({ mantissa: scaledMantissa }));
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return (Error.NO_ERROR, Exp({ mantissa: descaledMantissa }));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp memory divisor)
internal
pure
returns (Error, Exp memory)
{
/*
We are doing this as:
getExp(mul(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(Error err0, uint256 numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({ mantissa: 0 }));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(Error err1, uint256 doubleScaledProductWithHalfScale) =
add(halfExpScale, doubleScaledProduct);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({ mantissa: 0 }));
}
(Error err2, uint256 product) =
div(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == Error.NO_ERROR);
return (Error.NO_ERROR, Exp({ mantissa: product }));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / 10**18;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if first Exp is greater than second Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
}
interface ExchangeRateModel {
function scale() external view returns (uint256);
function token() external view returns (address);
function getExchangeRate() external view returns (uint256);
function getMaxSwingRate(uint256 interval) external view returns (uint256);
function getFixedInterestRate(uint256 interval)
external
view
returns (uint256);
function getFixedExchangeRate(uint256 interval)
external
view
returns (uint256);
}
interface IERC20 {
function decimals() external view returns (uint8);
}
interface IAggregator {
function ref() external view returns (address);
function getReferenceData(string memory _base, string memory _quote) external view returns (uint256, uint256, uint256);
}
interface IPriceModel {
function getAssetPrice(address _asset) external view returns (uint256);
}
contract PriceOracleBand is Exponential {
// Flag for whether or not contract is paused.
bool public paused;
// Approximately 1 hour: 60 seconds/minute * 60 minutes/hour * 1 block/15 seconds.
uint256 public constant numBlocksPerPeriod = 240;
uint256 public constant maxSwingMantissa = (5 * 10**15); // 0.005
uint256 public constant MINIMUM_SWING = 10**15;
uint256 public constant MAXIMUM_SWING = 10**17;
uint256 public constant SECONDS_PER_WEEK = 604800;
/**
* @dev An administrator who can set the pending anchor value for assets.
* Set in the constructor.
*/
address public anchorAdmin;
/**
* @dev Pending anchor administrator for this contract.
*/
address public pendingAnchorAdmin;
/**
* @dev Address of the price poster.
* Set in the constructor.
*/
address public poster;
/**
* @dev The maximum allowed percentage difference between a new price and the anchor's price
* Set only in the constructor
*/
Exp public maxSwing;
/**
* @dev The maximum allowed percentage difference for all assets between a new price and the anchor's price
*/
mapping(address => Exp) public maxSwings;
/**
* @dev Mapping of asset addresses to exchange rate information.
* Dynamic changes in asset prices based on exchange rates.
* map: assetAddress -> ExchangeRateInfo
*/
struct ExchangeRateInfo {
address exchangeRateModel; // Address of exchange rate model contract
uint256 exchangeRate; // Exchange rate between token and wrapped token
uint256 maxSwingRate; // Maximum changing ratio of the exchange rate
uint256 maxSwingDuration; // Duration of maximum changing ratio of the exchange rate
}
mapping(address => ExchangeRateInfo) public exchangeRates;
/**
* @dev Mapping of asset addresses to asset addresses. Stable coin can share a price.
*
* map: assetAddress -> Reader
*/
struct Reader {
address asset; // Asset to read price
int256 decimalsDifference; // Standard decimal is 18, so this is equal to the decimal of `asset` - 18.
}
mapping(address => Reader) public readers;
/**
* @dev Mapping of asset addresses and their corresponding price in terms of Eth-Wei
* which is simply equal to AssetWeiPrice * 10e18. For instance, if OMG token was
* worth 5x Eth then the price for OMG would be 5*10e18 or Exp({mantissa: 5000000000000000000}).
* map: assetAddress -> Exp
*/
mapping(address => Exp) public _assetPrices;
/**
* @dev The address of the aggregator who gets the asset price.
*/
IAggregator public aggregator;
uint256 public constant AGGREGATOR_DECIMALS = 18;
/**
* @dev Mapping of asset addresses to symbol.
*/
mapping(address => string) public symbols;
/**
* @dev Mapping of asset addresses to priceModel.
*/
mapping(address => IPriceModel) public priceModels;
constructor(address _poster, uint256 _maxSwing) public {
anchorAdmin = msg.sender;
poster = _poster;
_setMaxSwing(_maxSwing);
}
/**
* @notice Do not pay into PriceOracle.
*/
receive() external payable {
revert();
}
enum OracleError { NO_ERROR, UNAUTHORIZED, FAILED_TO_SET_PRICE }
enum OracleFailureInfo {
ACCEPT_ANCHOR_ADMIN_PENDING_ANCHOR_ADMIN_CHECK,
SET_PAUSED_OWNER_CHECK,
SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK,
SET_PENDING_ANCHOR_PERMISSION_CHECK,
SET_PRICE_CALCULATE_SWING,
SET_PRICE_CAP_TO_MAX,
SET_PRICE_MAX_SWING_CHECK,
SET_PRICE_NO_ANCHOR_PRICE_OR_INITIAL_PRICE_ZERO,
SET_PRICE_PERMISSION_CHECK,
SET_PRICE_ZERO_PRICE,
SET_PRICES_PARAM_VALIDATION,
SET_PRICE_IS_READER_ASSET
}
/**
* @dev `msgSender` is msg.sender; `error` corresponds to enum OracleError;
* `info` corresponds to enum OracleFailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
*/
event OracleFailure(
address msgSender,
address asset,
uint256 error,
uint256 info,
uint256 detail
);
/**
* @dev Use this when reporting a known error from the price oracle or a non-upgradeable collaborator
* Using Oracle in name because we already inherit a `fail` function from ErrorReporter.sol
* via Exponential.sol
*/
function failOracle(
address _asset,
OracleError _err,
OracleFailureInfo _info
) internal returns (uint256) {
emit OracleFailure(msg.sender, _asset, uint256(_err), uint256(_info), 0);
return uint256(_err);
}
/**
* @dev Use this to report an error when set asset price.
* Give the `error` corresponds to enum Error as `_details`.
*/
function failOracleWithDetails(
address _asset,
OracleError _err,
OracleFailureInfo _info,
uint256 _details
) internal returns (uint256) {
emit OracleFailure(
msg.sender,
_asset,
uint256(_err),
uint256(_info),
_details
);
return uint256(_err);
}
struct Anchor {
// Floor(block.number / numBlocksPerPeriod) + 1
uint256 period;
// Price in ETH, scaled by 10**18
uint256 priceMantissa;
}
/**
* @dev Anchors by asset.
*/
mapping(address => Anchor) public anchors;
/**
* @dev Pending anchor prices by asset.
*/
mapping(address => uint256) public pendingAnchors;
/**
* @dev Emitted when a pending anchor is set.
* @param asset Asset for which to set a pending anchor.
* @param oldScaledPrice If an unused pending anchor was present, its value; otherwise 0.
* @param newScaledPrice The new scaled pending anchor price.
*/
event NewPendingAnchor(
address anchorAdmin,
address asset,
uint256 oldScaledPrice,
uint256 newScaledPrice
);
/**
* @notice Provides ability to override the anchor price for an asset.
* @dev Admin function to set the anchor price for an asset.
* @param _asset Asset for which to override the anchor price.
* @param _newScaledPrice New anchor price.
* @return uint 0=success, otherwise a failure (see enum OracleError for details).
*/
function _setPendingAnchor(address _asset, uint256 _newScaledPrice)
external
returns (uint256)
{
// Check caller = anchorAdmin.
// Note: Deliberately not allowing admin. They can just change anchorAdmin if desired.
if (msg.sender != anchorAdmin) {
return
failOracle(
_asset,
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PENDING_ANCHOR_PERMISSION_CHECK
);
}
uint256 _oldScaledPrice = pendingAnchors[_asset];
pendingAnchors[_asset] = _newScaledPrice;
emit NewPendingAnchor(
msg.sender,
_asset,
_oldScaledPrice,
_newScaledPrice
);
return uint256(OracleError.NO_ERROR);
}
/**
* @dev Emitted for all exchangeRates changes.
*/
event SetExchangeRate(
address asset,
address exchangeRateModel,
uint256 exchangeRate,
uint256 maxSwingRate,
uint256 maxSwingDuration
);
event SetMaxSwingRate(
address asset,
uint256 oldMaxSwingRate,
uint256 newMaxSwingRate,
uint256 maxSwingDuration
);
/**
* @dev Emitted for all readers changes.
*/
event ReaderPosted(
address asset,
address oldReader,
address newReader,
int256 decimalsDifference
);
/**
* @dev Emitted for max swing changes.
*/
event SetMaxSwing(uint256 maxSwing);
/**
* @dev Emitted for max swing changes.
*/
event SetMaxSwingForAsset(address asset, uint256 maxSwing);
/**
* @dev Emitted for aggregator changes.
*/
event SetAggregator(IAggregator oldAggregator, IAggregator aggregator);
/**
* @dev Emitted for symbol changes.
*/
event SetAssetSymbol(address asset, string symbol);
/**
* @dev Emitted for priceModel changes.
*/
event SetAssetPriceModel(address asset, IPriceModel priceModel);
/**
* @dev Emitted for all price changes.
*/
event PricePosted(
address asset,
uint256 previousPriceMantissa,
uint256 requestedPriceMantissa,
uint256 newPriceMantissa
);
/**
* @dev Emitted if this contract successfully posts a capped-to-max price.
*/
event CappedPricePosted(
address asset,
uint256 requestedPriceMantissa,
uint256 anchorPriceMantissa,
uint256 cappedPriceMantissa
);
/**
* @dev Emitted when admin either pauses or resumes the contract; `newState` is the resulting state.
*/
event SetPaused(bool newState);
/**
* @dev Emitted when `pendingAnchorAdmin` is changed.
*/
event NewPendingAnchorAdmin(
address oldPendingAnchorAdmin,
address newPendingAnchorAdmin
);
/**
* @dev Emitted when `pendingAnchorAdmin` is accepted, which means anchor admin is updated.
*/
event NewAnchorAdmin(address oldAnchorAdmin, address newAnchorAdmin);
/**
* @dev Emitted when `poster` is changed.
*/
event NewPoster(address oldPoster, address newPoster);
/**
* @notice Set `paused` to the specified state.
* @dev Admin function to pause or resume the contract.
* @param _requestedState Value to assign to `paused`.
* @return uint 0=success, otherwise a failure.
*/
function _setPaused(bool _requestedState) external returns (uint256) {
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
paused = _requestedState;
emit SetPaused(_requestedState);
return uint256(Error.NO_ERROR);
}
/**
* @notice Begins to transfer the right of anchor admin.
* The `_newPendingAnchorAdmin` must call `_acceptAnchorAdmin` to finalize the transfer.
* @dev Admin function to change the anchor admin.
* The `_newPendingAnchorAdmin` must call `_acceptAnchorAdmin` to finalize the transfer.
* @param _newPendingAnchorAdmin New pending anchor admin.
* @return uint 0=success, otherwise a failure.
*/
function _setPendingAnchorAdmin(address _newPendingAnchorAdmin)
external
returns (uint256)
{
// Check caller = anchorAdmin.
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK
);
}
// Save current value, if any, for inclusion in log.
address _oldPendingAnchorAdmin = pendingAnchorAdmin;
// Store pendingAdmin = newPendingAdmin.
pendingAnchorAdmin = _newPendingAnchorAdmin;
emit NewPendingAnchorAdmin(
_oldPendingAnchorAdmin,
_newPendingAnchorAdmin
);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of anchor admin rights. `msg.sender` must be `pendingAnchorAdmin`.
* @dev Admin function for pending anchor admin to accept role and update anchor admin`
* @return uint 0=success, otherwise a failure`
*/
function _acceptAnchorAdmin() external returns (uint256) {
// Check caller = pendingAnchorAdmin.
// `msg.sender` can't be zero.
if (msg.sender != pendingAnchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo
.ACCEPT_ANCHOR_ADMIN_PENDING_ANCHOR_ADMIN_CHECK
);
}
// Save current value for inclusion in log.
address _oldAnchorAdmin = anchorAdmin;
// Store admin = pendingAnchorAdmin.
anchorAdmin = pendingAnchorAdmin;
// Clear the pending value.
pendingAnchorAdmin = address(0);
emit NewAnchorAdmin(_oldAnchorAdmin, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice Set new poster.
* @dev Admin function to change of poster.
* @param _newPoster New poster.
* @return uint 0=success, otherwise a failure.
*
* TODO: Should we add a second arg to verify, like a checksum of `newAnchorAdmin` address?
*/
function _setPoster(address _newPoster) external returns (uint256) {
assert(poster != _newPoster);
// Check caller = anchorAdmin.
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PENDING_ANCHOR_ADMIN_OWNER_CHECK
);
}
// Save current value, if any, for inclusion in log.
address _oldPoster = poster;
// Store poster = newPoster.
poster = _newPoster;
emit NewPoster(_oldPoster, _newPoster);
return uint256(Error.NO_ERROR);
}
/**
* @notice Set new exchange rate model.
* @dev Function to set exchangeRateModel for an asset.
* @param _asset Asset to set the new `_exchangeRateModel`.
* @param _exchangeRateModel New `_exchangeRateModel` cnotract address,
* if the `_exchangeRateModel` is address(0), revert to cancle.
* @param _maxSwingDuration A value greater than zero and less than the seconds of a week.
* @return uint 0=success, otherwise a failure (see enum OracleError for details).
*/
function setExchangeRate(
address _asset,
address _exchangeRateModel,
uint256 _maxSwingDuration
) external returns (uint256) {
// Check caller = anchorAdmin.
if (msg.sender != anchorAdmin) {
return
failOracle(
_asset,
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PRICE_PERMISSION_CHECK
);
}
require(
_exchangeRateModel != address(0),
"setExchangeRate: exchangeRateModel cannot be a zero address."
);
require(
_maxSwingDuration > 0 && _maxSwingDuration <= SECONDS_PER_WEEK,
"setExchangeRate: maxSwingDuration cannot be zero, less than 604800 (seconds per week)."
);
uint256 _currentExchangeRate =
ExchangeRateModel(_exchangeRateModel).getExchangeRate();
require(
_currentExchangeRate > 0,
"setExchangeRate: currentExchangeRate not zero."
);
uint256 _maxSwingRate =
ExchangeRateModel(_exchangeRateModel).getMaxSwingRate(
_maxSwingDuration
);
require(
_maxSwingRate > 0 &&
_maxSwingRate <=
ExchangeRateModel(_exchangeRateModel).getMaxSwingRate(
SECONDS_PER_WEEK
),
"setExchangeRate: maxSwingRate cannot be zero, less than 604800 (seconds per week)."
);
exchangeRates[_asset].exchangeRateModel = _exchangeRateModel;
exchangeRates[_asset].exchangeRate = _currentExchangeRate;
exchangeRates[_asset].maxSwingRate = _maxSwingRate;
exchangeRates[_asset].maxSwingDuration = _maxSwingDuration;
emit SetExchangeRate(
_asset,
_exchangeRateModel,
_currentExchangeRate,
_maxSwingRate,
_maxSwingDuration
);
return uint256(OracleError.NO_ERROR);
}
/**
* @notice Set a new `maxSwingRate`.
* @dev Function to set exchange rate `maxSwingRate` for an asset.
* @param _asset Asset for which to set the exchange rate `maxSwingRate`.
* @param _maxSwingDuration Interval time.
* @return uint 0=success, otherwise a failure (see enum OracleError for details)
*/
function setMaxSwingRate(address _asset, uint256 _maxSwingDuration)
external
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
_asset,
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PRICE_PERMISSION_CHECK
);
}
require(
_maxSwingDuration > 0 && _maxSwingDuration <= SECONDS_PER_WEEK,
"setMaxSwingRate: maxSwingDuration cannot be zero, less than 604800 (seconds per week)."
);
ExchangeRateModel _exchangeRateModel =
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel);
uint256 _newMaxSwingRate =
_exchangeRateModel.getMaxSwingRate(_maxSwingDuration);
uint256 _oldMaxSwingRate = exchangeRates[_asset].maxSwingRate;
require(
_oldMaxSwingRate != _newMaxSwingRate,
"setMaxSwingRate: the same max swing rate."
);
require(
_newMaxSwingRate > 0 &&
_newMaxSwingRate <=
_exchangeRateModel.getMaxSwingRate(SECONDS_PER_WEEK),
"setMaxSwingRate: maxSwingRate cannot be zero, less than 31536000 (seconds per week)."
);
exchangeRates[_asset].maxSwingRate = _newMaxSwingRate;
exchangeRates[_asset].maxSwingDuration = _maxSwingDuration;
emit SetMaxSwingRate(
_asset,
_oldMaxSwingRate,
_newMaxSwingRate,
_maxSwingDuration
);
return uint256(OracleError.NO_ERROR);
}
/**
* @notice Entry point for updating prices.
* @dev Set reader for an asset.
* @param _asset Asset for which to set the reader.
* @param _readAsset Reader address, if the reader is address(0), cancel the reader.
* @return uint 0=success, otherwise a failure (see enum OracleError for details).
*/
function setReaders(address _asset, address _readAsset)
external
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
_asset,
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PRICE_PERMISSION_CHECK
);
}
address _oldReadAsset = readers[_asset].asset;
// require(_readAsset != _oldReadAsset, "setReaders: Old and new values cannot be the same.");
require(
_readAsset != _asset,
"setReaders: asset and readAsset cannot be the same."
);
readers[_asset].asset = _readAsset;
if (_readAsset == address(0)) readers[_asset].decimalsDifference = 0;
else
readers[_asset].decimalsDifference = int256(
IERC20(_asset).decimals() - IERC20(_readAsset).decimals()
);
emit ReaderPosted(
_asset,
_oldReadAsset,
_readAsset,
readers[_asset].decimalsDifference
);
return uint256(OracleError.NO_ERROR);
}
/**
* @notice Set `maxSwing` to the specified value.
* @dev Admin function to change of max swing.
* @param _maxSwing Value to assign to `maxSwing`.
* @return uint 0=success, otherwise a failure.
*/
function _setMaxSwing(uint256 _maxSwing) public returns (uint256) {
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
uint256 _oldMaxSwing = maxSwing.mantissa;
require(
_maxSwing != _oldMaxSwing,
"_setMaxSwing: Old and new values cannot be the same."
);
require(
_maxSwing >= MINIMUM_SWING && _maxSwing <= MAXIMUM_SWING,
"_setMaxSwing: 0.1% <= _maxSwing <= 10%."
);
maxSwing = Exp({ mantissa: _maxSwing });
emit SetMaxSwing(_maxSwing);
return uint256(Error.NO_ERROR);
}
/**
* @notice Set `maxSwing` for asset to the specified value.
* @dev Admin function to change of max swing.
* @param _asset Asset for which to set the `maxSwing`.
* @param _maxSwing Value to assign to `maxSwing`.
* @return uint 0=success, otherwise a failure.
*/
function _setMaxSwingForAsset(address _asset, uint256 _maxSwing)
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
uint256 _oldMaxSwing = maxSwings[_asset].mantissa;
require(
_maxSwing != _oldMaxSwing,
"_setMaxSwingForAsset: Old and new values cannot be the same."
);
require(
_maxSwing >= MINIMUM_SWING && _maxSwing <= MAXIMUM_SWING,
"_setMaxSwingForAsset: 0.1% <= _maxSwing <= 10%."
);
maxSwings[_asset] = Exp({ mantissa: _maxSwing });
emit SetMaxSwingForAsset(_asset, _maxSwing);
return uint256(Error.NO_ERROR);
}
function _setMaxSwingForAssetBatch(
address[] calldata _assets,
uint256[] calldata _maxSwings
) external {
require(
_assets.length == _maxSwings.length,
"_setMaxSwingForAssetBatch: assets & maxSwings must match the current length."
);
for (uint256 i = 0; i < _assets.length; i++)
_setMaxSwingForAsset(_assets[i], _maxSwings[i]);
}
/**
* @notice Set `aggregator` to the specified address.
* @dev Admin function to change of aggregator.
* @param _aggregator Address to assign to `aggregator`.
* @return uint 0=success, otherwise a failure.
*/
function _setAggregator(IAggregator _aggregator)
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
require(
_aggregator.ref() != address(0),
"_setAggregator: This is not the aggregator contract!"
);
IAggregator _oldAggregator = aggregator;
require(
_aggregator != _oldAggregator,
"_setAggregator: Old and new address cannot be the same."
);
aggregator = _aggregator;
emit SetAggregator(_oldAggregator, _aggregator);
return uint256(Error.NO_ERROR);
}
/**
* @notice Set the `aggregator` to disabled.
* @dev Admin function to disable of aggregator.
* @return uint 0=success, otherwise a failure.
*/
function _disableAggregator()
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
IAggregator _oldAggregator = aggregator;
aggregator = IAggregator(0);
emit SetAggregator(_oldAggregator, IAggregator(0));
return uint256(Error.NO_ERROR);
}
/**
* @notice Set `symbol` for asset to the specified string.
* @dev Admin function to change of symbol.
* @param _asset Asset for which to set the `symbol`.
* @param _symbol String to assign to `symbol`.
* @return uint 0=success, otherwise a failure.
*/
function _setAssetSymbol(address _asset, string memory _symbol)
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
symbols[_asset] = _symbol;
emit SetAssetSymbol(_asset, _symbol);
return uint256(Error.NO_ERROR);
}
/**
* @notice Set `priceModels` for asset to the specified address.
* @dev Admin function to change of priceModels.
* @param _asset Asset for which to set the `priceModels`.
* @param _priceModel Address to assign to `priceModels`.
* @return uint 0=success, otherwise a failure.SetAssetPriceModel
*/
function _setAssetPriceModel(address _asset, IPriceModel _priceModel)
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
require(
_priceModel.getAssetPrice(_asset) >= 0,
"_setAssetPriceModel: This is not the priceModel contract!"
);
priceModels[_asset] = _priceModel;
emit SetAssetPriceModel(_asset, _priceModel);
return uint256(Error.NO_ERROR);
}
function _setAssetPriceModelBatch(
address[] calldata _assets,
IPriceModel[] calldata _priceModels
) external {
require(
_assets.length == _priceModels.length,
"_setAssetPriceModelBatch: assets & _priceModels must match the current length."
);
for (uint256 i = 0; i < _assets.length; i++)
_setAssetPriceModel(_assets[i], _priceModels[i]);
}
/**
* @notice Set the `priceModels` to disabled.
* @dev Admin function to disable of priceModels.
* @return uint 0=success, otherwise a failure.
*/
function _disablePriceModel(address _asset)
public
returns (uint256)
{
// Check caller = anchorAdmin
if (msg.sender != anchorAdmin) {
return
failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PAUSED_OWNER_CHECK
);
}
priceModels[_asset] = IPriceModel(0);
emit SetAssetPriceModel(_asset, IPriceModel(0));
return uint256(Error.NO_ERROR);
}
/**
* @notice Asset prices are provided by aggregator.
* @dev Get price of `asset` from aggregator.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case.
*/
function _getAssetAggregatorPrice(address _asset) internal view returns (uint256) {
if (aggregator == IAggregator(0))
return 0;
string memory _assetSymbol = symbols[_asset];
if (bytes(_assetSymbol).length == 0)
return 0;
(uint256 _aggregatorPrice, ,) = aggregator.getReferenceData(_assetSymbol, "USD");
return srcMul(
_aggregatorPrice,
10 ** (srcSub(36, srcAdd(uint256(IERC20(_asset).decimals()), AGGREGATOR_DECIMALS)))
);
}
function getAssetAggregatorPrice(address _asset) external view returns (uint256) {
return _getAssetAggregatorPrice(_asset);
}
/**
* @notice Asset prices are provided by priceModel.
* @dev Get price of `asset` from priceModel.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case.
*/
function _getPriceModelPrice(address _asset) internal view returns (uint256) {
IPriceModel _priceModel = priceModels[_asset];
if (_priceModel == IPriceModel(0))
return 0;
return _priceModel.getAssetPrice(_asset);
}
function getPriceModelPrice(address _asset) external view returns (uint256) {
return _getPriceModelPrice(_asset);
}
/**
* @notice Asset prices are provided by chain link or a reader.
* @dev Get price of `asset`.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or under unexpected case.
*/
function _getAssetPrice(address _asset) internal view returns (uint256) {
uint256 _assetPrice = _getAssetAggregatorPrice(_asset);
if (_assetPrice == 0)
_assetPrice = _getPriceModelPrice(_asset);
if (_assetPrice == 0)
return _getReaderPrice(_asset);
return _assetPrice;
}
function getAssetPrice(address _asset) external view returns (uint256) {
return _getAssetPrice(_asset);
}
/**
* @notice This is a basic function to read price, although this is a public function,
* It is not recommended, the recommended function is `assetPrices(asset)`.
* If `asset` does not has a reader to reader price, then read price from original
* structure `_assetPrices`;
* If `asset` has a reader to read price, first gets the price of reader, then
* `readerPrice * 10 ** |(18-assetDecimals)|`
* @dev Get price of `asset`.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset.
*/
function _getReaderPrice(address _asset) internal view returns (uint256) {
Reader storage reader = readers[_asset];
if (reader.asset == address(0)) return _assetPrices[_asset].mantissa;
uint256 readerPrice = _assetPrices[reader.asset].mantissa;
if (reader.decimalsDifference < 0)
return
srcMul(
readerPrice,
pow(10, uint256(0 - reader.decimalsDifference))
);
return srcDiv(readerPrice, pow(10, uint256(reader.decimalsDifference)));
}
function getReaderPrice(address _asset) external view returns (uint256) {
return _getReaderPrice(_asset);
}
/**
* @notice Retrieves price of an asset.
* @dev Get price for an asset.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or contract paused.
*/
function assetPrices(address _asset) internal view returns (uint256) {
// Note: zero is treated by the xSwap as an invalid
// price and will cease operations with that asset
// when zero.
//
// We get the price as:
//
// 1. If the contract is paused, return 0.
// 2. If the asset has an exchange rate model, the asset price is calculated based on the exchange rate.
// 3. Return price in `_assetPrices`, which may be zero.
if (paused) {
return 0;
} else {
uint256 _assetPrice = _getAssetPrice(_asset);
ExchangeRateInfo storage _exchangeRateInfo = exchangeRates[_asset];
if (_exchangeRateInfo.exchangeRateModel != address(0)) {
uint256 _scale =
ExchangeRateModel(_exchangeRateInfo.exchangeRateModel)
.scale();
uint256 _currentExchangeRate =
ExchangeRateModel(_exchangeRateInfo.exchangeRateModel)
.getExchangeRate();
uint256 _currentChangeRate;
Error _err;
(_err, _currentChangeRate) = mul(_currentExchangeRate, _scale);
if (_err != Error.NO_ERROR) return 0;
_currentChangeRate =
_currentChangeRate /
_exchangeRateInfo.exchangeRate;
// require(_currentExchangeRate >= _exchangeRateInfo.exchangeRate && _currentChangeRate <= _exchangeRateInfo.maxSwingRate, "assetPrices: Abnormal exchange rate.");
if (
_currentExchangeRate < _exchangeRateInfo.exchangeRate ||
_currentChangeRate > _exchangeRateInfo.maxSwingRate
) return 0;
uint256 _price;
(_err, _price) = mul(_assetPrice, _currentExchangeRate);
if (_err != Error.NO_ERROR) return 0;
return _price / _scale;
} else {
return _assetPrice;
}
}
}
/**
* @notice Retrieves price of an asset.
* @dev Get price for an asset.
* @param _asset Asset for which to get the price.
* @return Uint mantissa of asset price (scaled by 1e18) or zero if unset or contract paused.
*/
function getUnderlyingPrice(address _asset) external view returns (uint256) {
return assetPrices(_asset);
}
/**
* @dev Get exchange rate info of an asset in the time of `interval`.
* @param _asset Asset for which to get the exchange rate info.
* @param _interval Time to get accmulator interest rate.
* @return Asset price, exchange rate model address, the token that is using this exchange rate model,
* exchange rate model contract address,
* the token that is using this exchange rate model,
* scale between token and wrapped token,
* exchange rate between token and wrapped token,
* After the time of `_interval`, get the accmulator interest rate.
*/
function getExchangeRateInfo(address _asset, uint256 _interval)
external
view
returns (
uint256,
address,
address,
uint256,
uint256,
uint256
)
{
if (exchangeRates[_asset].exchangeRateModel == address(0))
return (_getReaderPrice(_asset), address(0), address(0), 0, 0, 0);
return (
_getReaderPrice(_asset),
exchangeRates[_asset].exchangeRateModel,
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel).token(),
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel).scale(),
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel)
.getExchangeRate(),
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel)
.getFixedInterestRate(_interval)
);
}
struct SetPriceLocalVars {
Exp price;
Exp swing;
Exp maxSwing;
Exp anchorPrice;
uint256 anchorPeriod;
uint256 currentPeriod;
bool priceCapped;
uint256 cappingAnchorPriceMantissa;
uint256 pendingAnchorMantissa;
}
/**
* @notice Entry point for updating prices.
* 1) If admin has set a `readerPrice` for this asset, then poster can not use this function.
* 2) Standard stablecoin has 18 deicmals, and its price should be 1e18,
* so when the poster set a new price for a token,
* `requestedPriceMantissa` = actualPrice * 10 ** (18-tokenDecimals),
* actualPrice is scaled by 10**18.
* @dev Set price for an asset.
* @param _asset Asset for which to set the price.
* @param _requestedPriceMantissa Requested new price, scaled by 10**18.
* @return Uint 0=success, otherwise a failure (see enum OracleError for details).
*/
function setPrice(address _asset, uint256 _requestedPriceMantissa)
external
returns (uint256)
{
// Fail when msg.sender is not poster
if (msg.sender != poster) {
return
failOracle(
_asset,
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PRICE_PERMISSION_CHECK
);
}
return setPriceInternal(_asset, _requestedPriceMantissa);
}
function setPriceInternal(address _asset, uint256 _requestedPriceMantissa)
internal
returns (uint256)
{
// re-used for intermediate errors
Error _err;
SetPriceLocalVars memory _localVars;
// We add 1 for currentPeriod so that it can never be zero and there's no ambiguity about an unset value.
// (It can be a problem in tests with low block numbers.)
_localVars.currentPeriod = (block.number / numBlocksPerPeriod) + 1;
_localVars.pendingAnchorMantissa = pendingAnchors[_asset];
_localVars.price = Exp({ mantissa: _requestedPriceMantissa });
if (exchangeRates[_asset].exchangeRateModel != address(0)) {
uint256 _currentExchangeRate =
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel)
.getExchangeRate();
uint256 _scale =
ExchangeRateModel(exchangeRates[_asset].exchangeRateModel)
.scale();
uint256 _currentChangeRate;
(_err, _currentChangeRate) = mul(_currentExchangeRate, _scale);
assert(_err == Error.NO_ERROR);
_currentChangeRate =
_currentChangeRate /
exchangeRates[_asset].exchangeRate;
require(
_currentExchangeRate >= exchangeRates[_asset].exchangeRate &&
_currentChangeRate <= exchangeRates[_asset].maxSwingRate,
"setPriceInternal: Abnormal exchange rate."
);
exchangeRates[_asset].exchangeRate = _currentExchangeRate;
}
if (readers[_asset].asset != address(0)) {
return
failOracle(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICE_IS_READER_ASSET
);
}
_localVars.maxSwing = maxSwings[_asset].mantissa == 0
? maxSwing
: maxSwings[_asset];
if (_localVars.pendingAnchorMantissa != 0) {
// let's explicitly set to 0 rather than relying on default of declaration
_localVars.anchorPeriod = 0;
_localVars.anchorPrice = Exp({
mantissa: _localVars.pendingAnchorMantissa
});
// Verify movement is within max swing of pending anchor (currently: 10%)
(_err, _localVars.swing) = calculateSwing(
_localVars.anchorPrice,
_localVars.price
);
if (_err != Error.NO_ERROR) {
return
failOracleWithDetails(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICE_CALCULATE_SWING,
uint256(_err)
);
}
// Fail when swing > maxSwing
// if (greaterThanExp(_localVars.swing, maxSwing)) {
if (greaterThanExp(_localVars.swing, _localVars.maxSwing)) {
return
failOracleWithDetails(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICE_MAX_SWING_CHECK,
_localVars.swing.mantissa
);
}
} else {
_localVars.anchorPeriod = anchors[_asset].period;
_localVars.anchorPrice = Exp({
mantissa: anchors[_asset].priceMantissa
});
if (_localVars.anchorPeriod != 0) {
// (_err, _localVars.priceCapped, _localVars.price) = capToMax(_localVars.anchorPrice, _localVars.price);
(_err, _localVars.priceCapped, _localVars.price) = capToMax(
_localVars.anchorPrice,
_localVars.price,
_localVars.maxSwing
);
if (_err != Error.NO_ERROR) {
return
failOracleWithDetails(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICE_CAP_TO_MAX,
uint256(_err)
);
}
if (_localVars.priceCapped) {
// save for use in log
_localVars.cappingAnchorPriceMantissa = _localVars
.anchorPrice
.mantissa;
}
} else {
// Setting first price. Accept as is (already assigned above from _requestedPriceMantissa) and use as anchor
_localVars.anchorPrice = Exp({
mantissa: _requestedPriceMantissa
});
}
}
// Fail if anchorPrice or price is zero.
// zero anchor represents an unexpected situation likely due to a problem in this contract
// zero price is more likely as the result of bad input from the caller of this function
if (isZeroExp(_localVars.anchorPrice)) {
// If we get here price could also be zero, but it does not seem worthwhile to distinguish the 3rd case
return
failOracle(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo
.SET_PRICE_NO_ANCHOR_PRICE_OR_INITIAL_PRICE_ZERO
);
}
if (isZeroExp(_localVars.price)) {
return
failOracle(
_asset,
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICE_ZERO_PRICE
);
}
// BEGIN SIDE EFFECTS
// Set pendingAnchor = Nothing
// Pending anchor is only used once.
if (pendingAnchors[_asset] != 0) {
pendingAnchors[_asset] = 0;
}
// If currentPeriod > anchorPeriod:
// Set anchors[_asset] = (currentPeriod, price)
// The new anchor is if we're in a new period or we had a pending anchor, then we become the new anchor
if (_localVars.currentPeriod > _localVars.anchorPeriod) {
anchors[_asset] = Anchor({
period: _localVars.currentPeriod,
priceMantissa: _localVars.price.mantissa
});
}
uint256 _previousPrice = _assetPrices[_asset].mantissa;
setPriceStorageInternal(_asset, _localVars.price.mantissa);
emit PricePosted(
_asset,
_previousPrice,
_requestedPriceMantissa,
_localVars.price.mantissa
);
if (_localVars.priceCapped) {
// We have set a capped price. Log it so we can detect the situation and investigate.
emit CappedPricePosted(
_asset,
_requestedPriceMantissa,
_localVars.cappingAnchorPriceMantissa,
_localVars.price.mantissa
);
}
return uint256(OracleError.NO_ERROR);
}
// As a function to allow harness overrides
function setPriceStorageInternal(address _asset, uint256 _priceMantissa)
internal
{
_assetPrices[_asset] = Exp({ mantissa: _priceMantissa });
}
// abs(price - anchorPrice) / anchorPrice
function calculateSwing(Exp memory _anchorPrice, Exp memory _price)
internal
pure
returns (Error, Exp memory)
{
Exp memory numerator;
Error err;
if (greaterThanExp(_anchorPrice, _price)) {
(err, numerator) = subExp(_anchorPrice, _price);
// can't underflow
assert(err == Error.NO_ERROR);
} else {
(err, numerator) = subExp(_price, _anchorPrice);
// Given greaterThan check above, _price >= _anchorPrice so can't underflow.
assert(err == Error.NO_ERROR);
}
return divExp(numerator, _anchorPrice);
}
// Base on the current anchor price, get the final valid price.
function capToMax(
Exp memory _anchorPrice,
Exp memory _price,
Exp memory _maxSwing
)
internal
pure
returns (
Error,
bool,
Exp memory
)
{
Exp memory one = Exp({ mantissa: mantissaOne });
Exp memory onePlusMaxSwing;
Exp memory oneMinusMaxSwing;
Exp memory max;
Exp memory min;
// re-used for intermediate errors
Error err;
(err, onePlusMaxSwing) = addExp(one, _maxSwing);
if (err != Error.NO_ERROR) {
return (err, false, Exp({ mantissa: 0 }));
}
// max = _anchorPrice * (1 + _maxSwing)
(err, max) = mulExp(_anchorPrice, onePlusMaxSwing);
if (err != Error.NO_ERROR) {
return (err, false, Exp({ mantissa: 0 }));
}
// If _price > _anchorPrice * (1 + _maxSwing)
// Set _price = _anchorPrice * (1 + _maxSwing)
if (greaterThanExp(_price, max)) {
return (Error.NO_ERROR, true, max);
}
(err, oneMinusMaxSwing) = subExp(one, _maxSwing);
if (err != Error.NO_ERROR) {
return (err, false, Exp({ mantissa: 0 }));
}
// min = _anchorPrice * (1 - _maxSwing)
(err, min) = mulExp(_anchorPrice, oneMinusMaxSwing);
// We can't overflow here or we would have already overflowed above when calculating `max`
assert(err == Error.NO_ERROR);
// If _price < _anchorPrice * (1 - _maxSwing)
// Set _price = _anchorPrice * (1 - _maxSwing)
if (lessThanExp(_price, min)) {
return (Error.NO_ERROR, true, min);
}
return (Error.NO_ERROR, false, _price);
}
/**
* @notice Entry point for updating multiple prices.
* @dev Set prices for a variable number of assets.
* @param _assets A list of up to assets for which to set a price.
* Notice: 0 < _assets.length == _requestedPriceMantissas.length
* @param _requestedPriceMantissas Requested new prices for the assets, scaled by 10**18.
* Notice: 0 < _assets.length == _requestedPriceMantissas.length
* @return Uint values in same order as inputs.
* For each: 0=success, otherwise a failure (see enum OracleError for details)
*/
function setPrices(
address[] memory _assets,
uint256[] memory _requestedPriceMantissas
) external returns (uint256[] memory) {
uint256 numAssets = _assets.length;
uint256 numPrices = _requestedPriceMantissas.length;
uint256[] memory result;
// Fail when msg.sender is not poster
if (msg.sender != poster) {
result = new uint256[](1);
result[0] = failOracle(
address(0),
OracleError.UNAUTHORIZED,
OracleFailureInfo.SET_PRICE_PERMISSION_CHECK
);
return result;
}
if ((numAssets == 0) || (numPrices != numAssets)) {
result = new uint256[](1);
result[0] = failOracle(
address(0),
OracleError.FAILED_TO_SET_PRICE,
OracleFailureInfo.SET_PRICES_PARAM_VALIDATION
);
return result;
}
result = new uint256[](numAssets);
for (uint256 i = 0; i < numAssets; i++) {
result[i] = setPriceInternal(_assets[i], _requestedPriceMantissas[i]);
}
return result;
}
}
| x to the power of y power(base, exponent)/ | function pow(uint256 base, uint256 exponent) internal pure returns (uint256) {
if (exponent == 0) {
return 1;
return base;
return 0;
uint256 z = base;
for (uint256 i = 1; i < exponent; i++) z = srcMul(z, base);
return z;
}
}
| 5,467,999 |
/*
Copyright 2022 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { ERC721Enumerable } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { HedgiesRoles } from "./HedgiesRoles.sol";
/**
* @title Hedgies
* @author dYdX
*
* @notice The Hedgies NFT contract.
*/
contract Hedgies is
HedgiesRoles,
ERC721Enumerable,
Pausable
{
// ============ Structs ============
struct MerkleRoot {
bytes32 merkleRoot;
bytes ipfsCid;
}
struct TierMintingInformation {
uint256 unlockTimestamp;
uint256 maxSupply;
}
// ============ Events ============
event StartingIndexBlockSet(
uint256 startingIndexBlock
);
event StartingIndexValueSet(
uint256 startingIndexValue
);
event BaseURISet(
string baseURI
);
event MerkleRootSet(
MerkleRoot merkleRoot
);
event DistributionMintRateSet(
uint256 distributionMintRate
);
event DistributionOffsetSet(
uint256 distributionOffset
);
event FinalizedUri();
// ============ Constants ============
uint256 constant public NUM_TIERS = 3;
uint256 constant public DISTRIBUTION_BASE = 10 ** 18;
bytes32 immutable public PROVENANCE_HASH;
uint256 immutable public MAX_SUPPLY;
uint256 immutable public RESERVE_SUPPLY;
uint256 immutable public TIER_ZERO_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_ONE_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_TWO_MINTS_UNLOCK_TIMESTAMP;
uint256 immutable public TIER_ZERO_MINTS_MAX_SUPPLY;
uint256 immutable public TIER_ONE_MINTS_MAX_SUPPLY;
uint256 immutable public TIER_TWO_MINTS_MAX_SUPPLY;
// ============ State Variables ============
MerkleRoot public _MERKLE_ROOT_;
uint256 public _HEDGIE_DISTRIBUTION_MINT_RATE_;
uint256 public _HEDGIE_DISTRIBUTION_OFFSET_;
string public _BASE_URI_ = "";
bool public _URI_IS_FINALIZED_ = false;
mapping (address => bool) public _HAS_CLAIMED_HEDGIE_;
uint256 public _STARTING_INDEX_BLOCK_ = 0;
// Note: Packed into a shared storage slot.
bool public _STARTING_INDEX_SET_ = false;
uint248 public _STARTING_INDEX_VALUE_ = 0;
// ============ Constructor ============
constructor(
string[2] memory nameAndSymbol,
bytes32 provenanceHash,
uint256 reserveSupply,
bytes32 merkleRoot,
bytes memory ipfsCid,
uint256[3] memory mintTierTimestamps,
uint256[3] memory mintTierMaxSupplies,
uint256 maxSupply,
address[3] memory roleOwners,
uint256[2] memory mintToVariables
)
HedgiesRoles(roleOwners[0], roleOwners[1], roleOwners[2])
ERC721(nameAndSymbol[0], nameAndSymbol[1])
{
// Verify the mint tier information is all correct.
require(
(
reserveSupply <= mintTierMaxSupplies[0] &&
mintTierMaxSupplies[0] <= mintTierMaxSupplies[1] &&
mintTierMaxSupplies[1] <= mintTierMaxSupplies[2] &&
mintTierMaxSupplies[2] <= maxSupply
),
"Each mint tier must gte the previous, includes reserveSupply and maxSupply"
);
require(
(
mintTierTimestamps[0] < mintTierTimestamps[1] &&
mintTierTimestamps[1] < mintTierTimestamps[2]
),
"Each tier must unlock later than the previous one"
);
// Set the provenanceHash.
PROVENANCE_HASH = provenanceHash;
// Set the maxSupply.
MAX_SUPPLY = maxSupply;
// The reserve supply is the number of hedgies set aside for the team and giveaways.
RESERVE_SUPPLY = reserveSupply;
// The tier mint unlock timestamps.
TIER_ZERO_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[0];
TIER_ONE_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[1];
TIER_TWO_MINTS_UNLOCK_TIMESTAMP = mintTierTimestamps[2];
// The tier max supplies.
TIER_ZERO_MINTS_MAX_SUPPLY = mintTierMaxSupplies[0];
TIER_ONE_MINTS_MAX_SUPPLY = mintTierMaxSupplies[1];
TIER_TWO_MINTS_MAX_SUPPLY = mintTierMaxSupplies[2];
// Set the merkle-root for eligible minters.
_setMerkleRootAndCid(
merkleRoot,
ipfsCid
);
// Set the hedgie distribution information.
_setDistributionMintRate(mintToVariables[0]);
_setDistributionOffset(mintToVariables[1]);
}
// ============ Modifiers ============
modifier uriNotFinalized {
// Verify the sale has not been finalized.
require(
!_URI_IS_FINALIZED_,
'Cannot update once the sale has been finalized'
);
_;
}
// ============ External Admin-Only Functions ============
/**
* @notice Pause this contract.
*/
function pause()
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_pause();
}
/**
* @notice Unpause this contract.
*/
function unpause()
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_unpause();
}
/**
* @notice Set the sale of the collection as finalized, preventing the baseURI from
* being updated again.
* @dev Emits finalized event.
*/
function finalize()
external
uriNotFinalized
onlyRole(DEFAULT_ADMIN_ROLE)
{
_URI_IS_FINALIZED_ = true;
emit FinalizedUri();
}
/**
* @notice Mint a hedgie to a specific address up to the reserve supply.
*
* Important: The reserve supply should be minted before the sale is enabled.
*
* @param maxMint The maximum number of NFTs to mint in one call to the function.
* @param recipient The address to mint the token to.
*/
function reserveHedgies(
uint256 maxMint,
address recipient
)
external
whenNotPaused
onlyRole(RESERVER_ROLE)
{
// Get supply and NFTs to mint.
uint256 supply = totalSupply();
uint256 hedgiesToMint = Math.min(maxMint, RESERVE_SUPPLY - supply);
require(
hedgiesToMint > 0,
"Cannot premint once max premint supply has been reached"
);
// Mint each NFT sequentially.
for (uint256 i = 0; i < hedgiesToMint; i++) {
// Use _mint() instead of _safeMint() since we don't plan to mint to any smart contracts.
_mint(recipient, supply + i);
}
}
/**
* @notice Mint a hedgie to a specific address.
*
* @param recipient The address to mint the token to.
* @param tokenId The id of the token to mint.
*/
function mintHedgieTo(
address recipient,
uint256 tokenId
)
external
whenNotPaused
onlyRole(MINTER_ROLE)
{
// Do not mint tokenId that should have been minted by now.
require(
tokenId >= TIER_TWO_MINTS_MAX_SUPPLY,
"Cannot mint token with tokenId lte tier two maxSupply"
);
// Do not mint tokens with invalid tokenIds.
// Prevents supply > MAX_SUPPLY as no duplicate tokenIds are allowed either.
require(
tokenId < MAX_SUPPLY,
"Cannot mint token with tokenId greater than maxSupply"
);
uint256 supply = totalSupply();
// Do not begin minting until all hedgies from tier 2 are minted.
require(
supply >= TIER_TWO_MINTS_MAX_SUPPLY,
"Cannot mint token for distribution before sale has completed"
);
// Verify that the maximum distributable supply at this timestamp has not been exceeded.
// Note: If _HEDGIE_DISTRIBUTION_OFFSET_ >= block.timestamp this call will revert.
uint256 availableHedgiesToMint = (
_HEDGIE_DISTRIBUTION_MINT_RATE_* (
block.timestamp - _HEDGIE_DISTRIBUTION_OFFSET_
) / DISTRIBUTION_BASE
);
require(
supply < availableHedgiesToMint + TIER_TWO_MINTS_MAX_SUPPLY,
'At the current timestamp supply is capped for distributing'
);
// Use _mint() instead of _safeMint() since we don't plan to mint to any smart contracts.
_mint(recipient, tokenId);
}
/**
* @notice Set the mint rate to distribute Hedgies at.
* @dev Emits DistributionMintRateSet event from an internal call.
*
* @param distributionMintRate The mint rate to distribute Hedgies at.
*/
function setDistributionMintRate(
uint256 distributionMintRate
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setDistributionMintRate(distributionMintRate);
}
/**
* @notice Set the offset for the mint rate to distribute Hedgies at. This is the timestamp at
* which we consider distribution via mintHedgieTo to have started.
* @dev Emits DistributionOffsetSet event from an internal call.
*
* @param distributionOffset The offset for the mint rate to distribute Hedgies at.
*/
function setDistributionOffset(
uint256 distributionOffset
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setDistributionOffset(distributionOffset);
}
/**
* @notice Set the base URI which determines the metadata URI for all tokens.
* Note: this call will revert if the contract is finalized.
* @dev Emits BaseURISet event.
*
* @param baseURI The URI that determines the metadata URI for all tokens.
*/
function setBaseURI(
string calldata baseURI
)
external
uriNotFinalized
onlyRole(DEFAULT_ADMIN_ROLE)
{
// Set the base URI.
_BASE_URI_ = baseURI;
emit BaseURISet(baseURI);
}
/**
* @notice Update the Merkle root and CID for the minting tiers. This should not be necessary
* since these values should be set when the contract is constructed. This function is
* provided just in case.
* @dev Emits MerkleRootSet event from an internal call.
*
* @param merkleRoot The root of the Merkle tree that proves who is eligible for distribution.
* @param ipfsCid The content identifier in IPFS for the Merkle tree.
*/
function setMerkleRootAndCid(
bytes32 merkleRoot,
bytes calldata ipfsCid
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setMerkleRootAndCid(merkleRoot, ipfsCid);
}
// ============ Other External Functions ============
/**
* @notice Mint a Hedgie if the tier 1 supply has not been reached. If we haven't set the starting index
* and this is the last token to be sold from tier 1, set the starting index block.
* @dev Emits StartingIndexBlockSet event from an internal call.
*
* @param tier The tier of the account minting a Hedgie.
* @param merkleProof The proof verifying the account is in the tier they are claiming to be in.
*/
function mintHedgie(
uint256 tier,
bytes32[] calldata merkleProof
)
external
whenNotPaused
{
// Get the tier minting information and verify that it is past the time when tier minting started.
TierMintingInformation memory tierMintingInformation = getMintsAndMintTimeForTier(tier);
require(
block.timestamp >= tierMintingInformation.unlockTimestamp,
"Tier minting is not yet allowed"
);
uint256 mintIndex = totalSupply();
// Verify the reserve supply has been minted.
require(
mintIndex >= RESERVE_SUPPLY,
"Not all Hedgies from the reserve supply have been minted"
);
// Verify the mint index is not past the max supply for the tier.
// Note: First ID to be minted is 0, and last to be minted is TIER_TWO_MINTS_MAX_SUPPLY - 1.
require(
mintIndex < tierMintingInformation.maxSupply,
"No Hedgies left to mint at this tier"
);
// The final tier is open to all.
if (tier < NUM_TIERS - 1) {
// Verify the address has not already minted.
require(
!_HAS_CLAIMED_HEDGIE_[msg.sender],
'Sender already claimed'
);
// Check if address is in the tier. The final tier is open to all.
require(
isAddressEligible(msg.sender, tier, merkleProof),
'Invalid Merkle proof'
);
// Mark the sender as having claimed.
_HAS_CLAIMED_HEDGIE_[msg.sender] = true;
}
// Use _mint() instead of _safeMint() since any contract calling this must be directly doing so.
_mint(msg.sender, mintIndex);
// Set the starting index block automatically when minting the last token.
if (mintIndex == TIER_TWO_MINTS_MAX_SUPPLY - 1) {
_setStartingIndexBlock(block.number);
}
}
/**
* @notice Set the starting index using the previously determined block number.
* @dev Emits StartingIndexBlockSet event from an internal call and StartingIndexValueSet event.
*/
function setStartingIndex()
external
{
// Verify the starting index has not been set.
require(
!_STARTING_INDEX_SET_,
"Starting index is already set"
);
// Verify the starting block has already been set.
uint256 startingIndexBlock = _STARTING_INDEX_BLOCK_;
require(
startingIndexBlock != 0,
"Starting index block must be set"
);
// Ensure the starting index block is within 256 blocks exclusive of the previous block
// and is not the current block as it has no blockHash yet.
// https://docs.soliditylang.org/en/v0.8.11/units-and-global-variables.html#block-and-transaction-properties
uint256 prevBlock = block.number - 1;
uint256 blockDifference = prevBlock - startingIndexBlock;
// If needed, set the starting index block to be within 256 of the current block.
if (blockDifference >= 256) {
startingIndexBlock = prevBlock - (blockDifference % 256);
_setStartingIndexBlock(startingIndexBlock);
}
// Set the starting index.
uint248 startingIndexValue = uint248(
uint256(blockhash(startingIndexBlock)) % MAX_SUPPLY
);
// Note: Packed into a shared storage slot.
_STARTING_INDEX_VALUE_ = startingIndexValue;
_STARTING_INDEX_SET_ = true;
emit StartingIndexValueSet(startingIndexValue);
}
// ============ Public Functions ============
/**
* @notice Get params for a minting tier: the unlock timestamp and number of mints available.
*
* @param tier The tier being checked for its unlock timestamp and number of total mints.
*/
function getMintsAndMintTimeForTier(
uint256 tier
)
public
view
returns (TierMintingInformation memory)
{
// Verify the tier is a valid mint tier.
require(
tier < NUM_TIERS,
"Invalid tier provided"
);
// Return the information for the tier being requested.
if (tier == 0) {
return TierMintingInformation({
unlockTimestamp: TIER_ZERO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ZERO_MINTS_MAX_SUPPLY
});
}
if (tier == 1) {
return TierMintingInformation({
unlockTimestamp: TIER_ONE_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ONE_MINTS_MAX_SUPPLY
});
}
return TierMintingInformation({
unlockTimestamp: TIER_TWO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_TWO_MINTS_MAX_SUPPLY
});
}
/**
* @notice Check if an address is eligible for a given tier.
*
* @param ethereumAddress The address trying to mint a hedige.
* @param tier The tier to check.
* @param merkleProof The Merkle proof proving that (ethereumAddress, tier) is in the tree.
*/
function isAddressEligible(
address ethereumAddress,
uint256 tier,
bytes32[] calldata merkleProof
)
public
view
returns (bool)
{
// Get the node of the ethereumAddress and tier and verify it is in the Merkle tree.
bytes32 node = keccak256(abi.encodePacked(ethereumAddress, tier));
return MerkleProof.verify(merkleProof, _MERKLE_ROOT_.merkleRoot, node);
}
/**
* @notice See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(AccessControl, ERC721Enumerable)
returns (bool)
{
return (
AccessControl.supportsInterface(interfaceId) ||
ERC721Enumerable.supportsInterface(interfaceId)
);
}
// ============ Internal Functions ============
/**
* @notice Get the base URI.
*/
function _baseURI()
internal
view
override
returns (string memory)
{
// Get the base URI.
return _BASE_URI_;
}
/**
* @notice Set the starting index.
* @dev Emits StartingIndexBlockSet event.
*
* @param startingIndexBlock The block number to set the starting index to.
*/
function _setStartingIndexBlock(
uint256 startingIndexBlock
)
internal
{
_STARTING_INDEX_BLOCK_ = startingIndexBlock;
emit StartingIndexBlockSet(startingIndexBlock);
}
/**
* @notice Set the merkle root and CID.
* @dev Emits MerkleRootSet event.
*
* @param merkleRoot The root of the Merkle tree that proves who is eligible for distribution.
* @param ipfsCid The content identifier in IPFS for the Merkle tree data.
*/
function _setMerkleRootAndCid(
bytes32 merkleRoot,
bytes memory ipfsCid
)
internal
{
// Get the full Merkle root and set _MERKLE_ROOT_ in storage.
MerkleRoot memory fullMerkleRoot = MerkleRoot({
merkleRoot: merkleRoot,
ipfsCid: ipfsCid
});
_MERKLE_ROOT_ = fullMerkleRoot;
emit MerkleRootSet(fullMerkleRoot);
}
/**
* @notice Set the mint rate to distribute Hedgies at.
* @dev Emits DistributionMintRateSet event.
*
* @param distributionMintRate The mint rate to distribute Hedgies at.
*/
function _setDistributionMintRate(
uint256 distributionMintRate
)
internal
{
// Set the distribution mint rate.
_HEDGIE_DISTRIBUTION_MINT_RATE_ = distributionMintRate;
emit DistributionMintRateSet(distributionMintRate);
}
/**
* @notice Set the offset for the mint rate to distribute Hedgies at. This is the timestamp at
* which we consider distribution via mintHedgieTo to have started.
* @dev Emits DistributionOffsetSet event.
*
* @param distributionOffset The offset for the mint rate to distribute Hedgies at.
*/
function _setDistributionOffset(
uint256 distributionOffset
)
internal
{
// Set the offset for the distribution mint rate.
_HEDGIE_DISTRIBUTION_OFFSET_ = distributionOffset;
emit DistributionOffsetSet(distributionOffset);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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 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 (security/Pausable.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/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 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
/*
Copyright 2022 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title HedgiesRoles
* @author dYdX
*
* @notice Defines roles used in the Hedgies contract. The hierarchy of roles and powers
* of each role are described below.
*
* Roles:
*
* DEFAULT_ADMIN_ROLE
* | -> May add or remove users from any of the below roles it manages.
* |
* +-- RESERVER_ROLE
* | -> May reserve to any address as long as reserve supply has not been met.
* |
* +-- MINTER_ROLE
* -> May mint to any address as long as mint supply has not been met.
*/
contract HedgiesRoles is
AccessControl
{
bytes32 public constant RESERVER_ROLE = keccak256('RESERVER_ROLE');
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
constructor(
address admin,
address reserver,
address minter
) {
// Assign roles.
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(RESERVER_ROLE, reserver);
_grantRole(MINTER_ROLE, minter);
}
}
// 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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/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 v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| Get params for a minting tier: the unlock timestamp and number of mints available. tier The tier being checked for its unlock timestamp and number of total mints./ Verify the tier is a valid mint tier. Return the information for the tier being requested. | function getMintsAndMintTimeForTier(
uint256 tier
)
public
view
returns (TierMintingInformation memory)
{
require(
tier < NUM_TIERS,
"Invalid tier provided"
);
if (tier == 0) {
return TierMintingInformation({
unlockTimestamp: TIER_ZERO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ZERO_MINTS_MAX_SUPPLY
});
}
if (tier == 1) {
return TierMintingInformation({
unlockTimestamp: TIER_ONE_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_ONE_MINTS_MAX_SUPPLY
});
}
return TierMintingInformation({
unlockTimestamp: TIER_TWO_MINTS_UNLOCK_TIMESTAMP,
maxSupply: TIER_TWO_MINTS_MAX_SUPPLY
});
}
| 1,063,370 |
./partial_match/1/0x982BAf549A10EbE316E1a9a400C465b92864f620/sources/DOGES.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Doges Coin", "DOGES") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 15;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 10;
uint256 _sellMarketingFee = 15;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 10;
uint256 _feeDenominator = 100;
uint256 totalSupply = 1_000_000 * 1e18;
feeDenominator = _feeDenominator;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(devWallet, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(devWallet, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 2,650,042 |
pragma solidity ^0.8.6;
import "@gnosis.pm/zodiac/contracts/core/Module.sol";
import {SnapshotXProposalRelayer} from "./ProposalRelayer.sol";
contract SnapshotXL1Executor is Module, SnapshotXProposalRelayer {
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH =
0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
bytes32 public constant TRANSACTION_TYPEHASH =
0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad;
// keccak256(
// "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)"
// );
// counter that is incremented each time a proposal is received.
uint256 public proposalIndex = 0;
//The state of a proposal index exists in one of the 5 categories. This can be queried using the getProposalState view function
enum ProposalState {
NotReceived,
Received,
Executing,
Executed,
Cancelled
}
struct ProposalExecution {
bytes32[] txHashes; //array of Transaction Hashes for each transaction in the proposal
uint256 executionCounter; //counter which stores the number of transaction in the proposal that have so far been executed. This ensures that transactions cannot be executed twice and that transactions are executed in the predefined order.
bool cancelled;
//timelock? (ignoring for now)
}
mapping(uint256 => ProposalExecution) public proposalIndexToProposalExecution;
// ######## EVENTS ########
event SnapshotXL1ExecutorSetUpComplete(
address indexed initiator,
address indexed _owner,
address indexed _avatar,
address _target,
uint256 _decisionExecutorL2,
address _starknetCore
);
event ProposalReceived(uint256 proposalIndex);
event TransactionExecuted(uint256 proposalIndex, bytes32 txHash);
event ProposalExecuted(uint256 proposalIndex);
event ProposalCancelled(uint256 proposalIndex);
// @dev
// @param _owner
// @param _avatar The address of the programmable ethereum account contract that this module is linked to. the contract must implement IAvatar.sol. Gnosis is safe is one implementation.
// @param _target
// @param _decisionExecutorL2 is the starknet address of the Decision Executor contract for this DAO. This contract will be the L2 end of the L2 -> L1 message bridge
constructor(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _decisionExecutorL2
) {
bytes memory initParams = abi.encode(
_owner,
_avatar,
_target,
_starknetCore,
_decisionExecutorL2
);
setUp(initParams);
}
function setUp(bytes memory initParams) public override initializer {
(
address _owner,
address _avatar,
address _target,
address _starknetCore,
uint256 _decisionExecutorL2
) = abi.decode(initParams, (address, address, address, address, uint256));
__Ownable_init();
transferOwnership(_owner);
avatar = _avatar;
target = _target;
setUpSnapshotXProposalRelayer(_starknetCore, _decisionExecutorL2);
emit SnapshotXL1ExecutorSetUpComplete(msg.sender, _owner, _avatar, _target, _decisionExecutorL2, _starknetCore);
}
//Consumes message from L2 containing finalized proposal, checks transaction hashes are valid, then stores transactions hashes
function receiveProposal(uint256 executionDetails, uint256 hasPassed, bytes32[] memory txHashes) public {
//External call will fail if finalized proposal message was not received on L1.
_receiveFinalizedProposal(executionDetails, hasPassed);
//Check that proposal passed
require(hasPassed!=0, 'Proposal did not pass');
//check that execution details are valid
require(bytes32(executionDetails) == keccak256(abi.encode(txHashes)), 'Invalid execution');
proposalIndexToProposalExecution[proposalIndex].txHashes = txHashes;
proposalIndex+=0;
emit ProposalReceived(proposalIndex);
}
//Test function to cause an equivalent state change to receiveProposal without having to consume a starknet message.
function receiveProposalTest(uint256 executionDetails, uint256 hasPassed, bytes32[] memory _txHashes) public {
//Check that proposal passed
require(hasPassed==1, 'Proposal did not pass');
//Check proposal contains at least one transaction
require(_txHashes.length > 0, "proposal must contain transactions");
//check that transactions are valid
require(bytes32(executionDetails) == keccak256(abi.encode(_txHashes)), 'Invalid execution');
proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes;
proposalIndex++; //uint256(0); // Very weird error here: AssertionError: Expected "1" to be equal 0 when I increment by 1. ignored for now
emit ProposalReceived(proposalIndex);
}
/// @dev Cancels a proposal.
/// @param _proposalIndexes array of proposals to cancel.
function cancelProposals(uint256[] memory _proposalIndexes) public onlyOwner {
for (uint256 i = 0; i < _proposalIndexes.length; i++) {
require(
getProposalState(_proposalIndexes[i]) != ProposalState.NotReceived,
"Proposal not received, nothing to cancel"
);
require(
getProposalState(_proposalIndexes[i]) != ProposalState.Executed,
"Execution completed, nothing to cancel"
);
require(
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled == false,
"proposal is already canceled"
);
//to cancel a proposal, we can set the execution counter for the proposal to the number of transactions in the proposal.
//We must also set a boolean in the Proposal Execution struct to true, without this there would be no way for the state to differentiate between a cancelled and an executed proposal.
proposalIndexToProposalExecution[_proposalIndexes[i]].executionCounter = proposalIndexToProposalExecution[_proposalIndexes[i]].txHashes.length;
proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled = true;
emit ProposalCancelled(_proposalIndexes[i]);
}
}
function executeProposalTx(uint256 _proposalIndex, address target, uint256 value, bytes memory data, Enum.Operation operation) public {
bytes32 txHash = getTransactionHash(target, value, data, operation);
//If all the Txs have been executed then the executionCounter will be exceed the length of the txHash array so the state look up will return nothing
require(
proposalIndexToProposalExecution[_proposalIndex].txHashes[
proposalIndexToProposalExecution[_proposalIndex].executionCounter
] == txHash,
"Invalid transaction or invalid transaction order"
);
proposalIndexToProposalExecution[_proposalIndex].executionCounter++;
require(
exec(target, value, data, operation),
"Module transaction failed"
);
emit TransactionExecuted(_proposalIndex, txHash);
//if final transaction, emit ProposalExecuted event - could remove to reduce gas costs a bit and infer offchain
if (getProposalState(_proposalIndex) == ProposalState.Executed) {
emit ProposalExecuted(_proposalIndex);
}
}
//Wrapper function around executeProposalTx to execute all transactions in a proposal with a single transaction.
//Will reach the block gas limit if too many/large transactions are included.
function executeProposalTxBatch(uint256 _proposalIndex, address[] memory targets, uint256[] memory values, bytes[] memory data, Enum.Operation[] memory operations) public {
//execute each transaction individually
for (uint256 i = 0; i < targets.length; i++) {
executeProposalTx(_proposalIndex, targets[i], values[i], data[i], operations[i]);
}
}
//###### VIEW FUNCTIONS ######
function getProposalState(uint256 _proposalIndex) public view returns (ProposalState) {
ProposalExecution storage proposalExecution = proposalIndexToProposalExecution[_proposalIndex];
if (proposalExecution.txHashes.length == 0) {
return ProposalState.NotReceived;
} else if (proposalExecution.cancelled) {
return ProposalState.Cancelled;
} else if (proposalExecution.executionCounter == 0) {
return ProposalState.Received;
} else if (proposalExecution.txHashes.length == proposalExecution.executionCounter) {
return ProposalState.Executed;
} else {
return ProposalState.Executing;
}
}
function getNumOfTxInProposal(uint256 _proposalIndex) public view returns (uint256) {
return proposalIndexToProposalExecution[_proposalIndex].txHashes.length;
}
//returns hash of transaction at specified index in array.
//One can iterate through this up till isProposalExecuted to obtain all the Tx hashes in the proposal
function getTxHash(uint256 _proposalIndex, uint256 txIndex) public view returns (bytes32) {
require(_proposalIndex < proposalIndex, "Invalid Proposal Index");
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].txHashes[txIndex];
}
//returns true if transaction specified by its index is executed
function isTxExecuted(uint256 _proposalIndex, uint256 txIndex) public view returns (bool) {
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].executionCounter > txIndex;
}
/// @dev Generates the data for the module transaction hash (required for signing)
function generateTransactionHashData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 nonce
) public view returns (bytes memory) {
uint256 chainId = block.chainid;
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)
);
bytes32 transactionHash = keccak256(
abi.encode(
TRANSACTION_TYPEHASH,
to,
value,
keccak256(data),
operation,
nonce
)
);
return
abi.encodePacked(
bytes1(0x19),
bytes1(0x01),
domainSeparator,
transactionHash
);
}
function getTransactionHash(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public view returns (bytes32) {
return
keccak256(
generateTransactionHashData(to, value, data, operation, 0)
);
}
} | returns hash of transaction at specified index in array.One can iterate through this up till isProposalExecuted to obtain all the Tx hashes in the proposal | function getTxHash(uint256 _proposalIndex, uint256 txIndex) public view returns (bytes32) {
require(_proposalIndex < proposalIndex, "Invalid Proposal Index");
require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length);
return proposalIndexToProposalExecution[_proposalIndex].txHashes[txIndex];
}
| 6,484,035 |
./partial_match/3/0x22962a4a71D09f34BAB99AabA5D34e6E35FF2f0c/sources/SmartStaking.sol | claim dividends for a particular token that user has stake in. You must check if the token is added first! _tokenAddr the token that the claim is made on/ | function _claim(address _tokenAddr) internal returns (uint) {
uint claimableAmount = calculateReward(_tokenAddr, msg.sender);
if (claimableAmount == 0) {
return claimableAmount;
}
userClaimableRewardPerStake[_tokenAddr][msg.sender] = tokenCummulativeRewardPerStake[_tokenAddr];
require(IERC20(rewardTokens[_tokenAddr]).transfer(msg.sender, claimableAmount), "Transfer failed");
emit Claimed(msg.sender, _tokenAddr, claimableAmount);
return claimableAmount;
}
| 5,324,154 |
./full_match/5/0x0F265cA07bBdF16700ae7E1C7e1efD04f6e22718/sources/_connext/smart-contracts/contracts/core/connext/libraries/AssetLogic.sol | Swaps a local bridge asset for the adopted asset using the stored stable swap Will not swap if the asset passed in is the adopted asset _key the hash of the canonical id and domain _asset - The address of the local asset to swap into the adopted asset _amount - The exact amount to receive out of the swap _maxIn - The most you will supply to the swap return The amount of local asset put into swap return The address of asset received post-swap/ If the adopted asset is the local asset, no need to swap. | function swapFromLocalAssetIfNeededForExactOut(
bytes32 _key,
address _asset,
uint256 _amount,
uint256 _maxIn
) internal returns (uint256, address) {
TokenConfig storage config = getConfig(_key);
address adopted = config.adopted;
if (adopted == _asset) {
return (_amount, adopted);
}
return _swapAssetOut(_key, _asset, adopted, _amount, _maxIn);
}
| 11,604,010 |
./full_match/1/0xAb291D8D2F52EC7a1A4930A8714F0adEc37aF9F1/sources/contracts/IUniswapV3Pool.sol | The interface for a Uniswap V3 Pool A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform to the ERC20 specification The pool interface is broken up into many smaller pieces | interface IUniswapV3Pool {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
function feeGrowthGlobal0X128() external view returns (uint256);
function feeGrowthGlobal1X128() external view returns (uint256);
function protocolFees() external view returns (uint128 token0, uint128 token1);
function liquidity() external view returns (uint128);
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
function tickBitmap(int16 wordPosition) external view returns (uint256);
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
function token0() external view returns (address);
function token1() external view returns (address);
pragma solidity >=0.5.0;
}
| 17,079,529 |
/*
Copyright 2018 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.4.24;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "../src/ERC20Token.sol";
import "@0x/contracts-exchange/contracts/src/interfaces/IExchange.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
// solhint-disable no-unused-vars
contract ReentrantERC20Token is
ERC20Token
{
using LibBytes for bytes;
// solhint-disable-next-line var-name-mixedcase
IExchange internal EXCHANGE;
bytes internal constant REENTRANCY_ILLEGAL_REVERT_REASON = abi.encodeWithSelector(
bytes4(keccak256("Error(string)")),
"REENTRANCY_ILLEGAL"
);
// All of these functions are potentially vulnerable to reentrancy
// We do not test any "noThrow" functions because `fillOrderNoThrow` makes a delegatecall to `fillOrder`
enum ExchangeFunction {
FILL_ORDER,
FILL_OR_KILL_ORDER,
BATCH_FILL_ORDERS,
BATCH_FILL_OR_KILL_ORDERS,
MARKET_BUY_ORDERS,
MARKET_SELL_ORDERS,
MATCH_ORDERS,
CANCEL_ORDER,
BATCH_CANCEL_ORDERS,
CANCEL_ORDERS_UP_TO,
SET_SIGNATURE_VALIDATOR_APPROVAL
}
uint8 internal currentFunctionId = 0;
constructor (address _exchange)
public
{
EXCHANGE = IExchange(_exchange);
}
/// @dev Set the current function that will be called when `transferFrom` is called.
/// @param _currentFunctionId Id that corresponds to function name.
function setCurrentFunction(uint8 _currentFunctionId)
external
{
currentFunctionId = _currentFunctionId;
}
/// @dev A version of `transferFrom` that attempts to reenter the Exchange contract.
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool)
{
// This order would normally be invalid, but it will be used strictly for testing reentrnacy.
// Any reentrancy checks will happen before any other checks that invalidate the order.
LibOrder.Order memory order;
// Initialize remaining null parameters
bytes memory signature;
LibOrder.Order[] memory orders;
uint256[] memory takerAssetFillAmounts;
bytes[] memory signatures;
bytes memory callData;
// Create callData for function that corresponds to currentFunctionId
if (currentFunctionId == uint8(ExchangeFunction.FILL_ORDER)) {
callData = abi.encodeWithSelector(
EXCHANGE.fillOrder.selector,
order,
0,
signature
);
} else if (currentFunctionId == uint8(ExchangeFunction.FILL_OR_KILL_ORDER)) {
callData = abi.encodeWithSelector(
EXCHANGE.fillOrKillOrder.selector,
order,
0,
signature
);
} else if (currentFunctionId == uint8(ExchangeFunction.BATCH_FILL_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.batchFillOrders.selector,
orders,
takerAssetFillAmounts,
signatures
);
} else if (currentFunctionId == uint8(ExchangeFunction.BATCH_FILL_OR_KILL_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.batchFillOrKillOrders.selector,
orders,
takerAssetFillAmounts,
signatures
);
} else if (currentFunctionId == uint8(ExchangeFunction.MARKET_BUY_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.marketBuyOrders.selector,
orders,
0,
signatures
);
} else if (currentFunctionId == uint8(ExchangeFunction.MARKET_SELL_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.marketSellOrders.selector,
orders,
0,
signatures
);
} else if (currentFunctionId == uint8(ExchangeFunction.MATCH_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.matchOrders.selector,
order,
order,
signature,
signature
);
} else if (currentFunctionId == uint8(ExchangeFunction.CANCEL_ORDER)) {
callData = abi.encodeWithSelector(
EXCHANGE.cancelOrder.selector,
order
);
} else if (currentFunctionId == uint8(ExchangeFunction.BATCH_CANCEL_ORDERS)) {
callData = abi.encodeWithSelector(
EXCHANGE.batchCancelOrders.selector,
orders
);
} else if (currentFunctionId == uint8(ExchangeFunction.CANCEL_ORDERS_UP_TO)) {
callData = abi.encodeWithSelector(
EXCHANGE.cancelOrdersUpTo.selector,
0
);
} else if (currentFunctionId == uint8(ExchangeFunction.SET_SIGNATURE_VALIDATOR_APPROVAL)) {
callData = abi.encodeWithSelector(
EXCHANGE.setSignatureValidatorApproval.selector,
address(0),
false
);
}
// Call Exchange function, swallow error
address(EXCHANGE).call(callData);
// Revert reason is 100 bytes
bytes memory returnData = new bytes(100);
// Copy return data
assembly {
returndatacopy(add(returnData, 32), 0, 100)
}
// Revert if function reverted with REENTRANCY_ILLEGAL error
require(!REENTRANCY_ILLEGAL_REVERT_REASON.equals(returnData));
// Transfer will return true if function failed for any other reason
return true;
}
} | Set the current function that will be called when `transferFrom` is called. _currentFunctionId Id that corresponds to function name. | function setCurrentFunction(uint8 _currentFunctionId)
external
{
currentFunctionId = _currentFunctionId;
}
| 2,482,581 |
./full_match/42/0x65ceA26FaFcfa5cd80428dFBd36e0B66535351c5/sources/FavorCurrency.sol | First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff) are the redemption addresses. account address to check is a redemption address All transfers to redemption address will trigger token burn. For transfer to succeed, canBurn must be true for redemption address return is `account` a redemption address/ | function isRedemptionAddress(address account) internal pure returns (bool) {
return uint160(account) < uint160(REDEMPTION_ADDRESS_COUNT) && uint160(account) != 0;
}
| 9,574,361 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IERC1155.sol";
import "./chainlink/LinkTokenInterface.sol";
import "./interfaces/IERC173.sol";
import "./interfaces/IERC165.sol";
import "./interfaces/IAavegotchi.sol";
import "./libraries/LibAppStorage.sol";
//import "@openzeppelin/contracts-upgradeable";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "hardhat/console.sol";
// All state variables are accessed through this struct
// To avoid name clashes and make clear a variable is a state variable
// state variable access starts with "s." which accesses variables in this struct
struct AppStorage {
// IERC165
mapping(bytes4 => bool) supportedInterfaces;
Raffle[6] raffles;
// Nonces for VRF keyHash from which randomness has been requested.
// Must stay in sync with VRFCoordinator[_keyHash][this]
// keyHash => nonce
mapping(bytes32 => uint256) nonces;
mapping(bytes32 => uint256) requestIdToRaffleId;
bytes32 keyHash;
uint96 fee;
address contractOwner;
IAavegotchi aavegotchiDiamond;
}
interface ERC20 {
function balanceOf(address account) 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 approve(address spender, uint256 amount) external returns (bool);
}
struct Raffle {
//an array of all the itemIds that have been entered
uint256[] itemsEntered;
//a mapping of who has entered what item
mapping(address => uint256) entrantsMapping;
address[] entrants;
uint256 brsMultiplier;
// vrf randomness
uint256 randomNumber;
// requested vrf random number
bool randomNumberPending;
bool raffleActive;
}
//a struct that can be returned in external view function (no nested mapping)
struct RaffleLite {
uint256 brsMultiplier;
uint256[] itemsEntered;
address[] entrants;
uint256 randomNumber;
uint256 winningIndex;
address winner;
uint blockReset;
}
// The minimum rangeStart is 0
// The maximum rangeEnd is raffleItem.totalEntered
// rangeEnd - rangeStart == number of ticket entered for raffle item by a entrant entry
struct Entry {
uint24 raffleItemIndex; // Which raffle item is entered into the raffleEnd
// used to prevent users from claiming prizes more than once
bool prizesClaimed;
uint112 rangeStart; // Raffle number. Value is between 0 and raffleItem.totalEntered - 1
uint112 rangeEnd; // Raffle number. Value is between 1 and raffleItem.totalEntered
}
struct RaffleItemPrize {
address prizeAddress; // ERC1155 token contract
uint96 prizeQuantity; // Number of ERC1155 tokens
uint256 prizeId; // ERC1155 token type
}
// Ticket numbers are numbers between 0 and raffleItem.totalEntered - 1 inclusive.
struct RaffleItem {
address ticketAddress; // ERC1155 token contract
uint256 ticketId; // ERC1155 token type
uint256 totalEntered; // Total number of ERC1155 tokens entered into raffle for this raffle item
RaffleItemPrize[] raffleItemPrizes; // Prizes that can be won for this raffle item
}
contract RafflesContract is IERC173, IERC165, Initializable {
// State variables are prefixed with s.
AppStorage internal s;
// Immutable values are prefixed with im_ to easily identify them in code
LinkTokenInterface internal im_link;
address internal im_vrfCoordinator;
address internal im_diamondAddress;
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`).
mapping(address => bool) isAuthorized;
ERC20 ghst;
RaffleLite[] completedRaffles;
function getHistoricalRaffles() public view returns(RaffleLite[] memory){
return completedRaffles;
}
function getHistoricalRaffle(uint256 _index) public view returns(RaffleLite memory){
return completedRaffles[_index];
}
function getCoordinator() public view returns(address){
return im_vrfCoordinator;
}
modifier onlyOwner{
require(msg.sender == s.contractOwner,"Failed: not contract owner");
_;
}
modifier onlyAuthorized{
require(isAuthorized[msg.sender] || msg.sender == s.contractOwner);
_;
}
function getAuthorized(address _user) public view returns(bool){
return isAuthorized[_user];
}
function setAuthorized(address _user) public onlyOwner{
isAuthorized[_user] = true;
}
function removeAuthorized(address _user) public onlyOwner{
isAuthorized[_user] = false;
}
function initialize (
address _aavegotchiDiamond,
address _contractOwner,
address _vrfCoordinator,
address _link,
bytes32 _keyHash,
uint256 _fee
) public initializer{
s.contractOwner = _contractOwner;
im_vrfCoordinator = _vrfCoordinator;
im_link = LinkTokenInterface(_link);
im_diamondAddress = _aavegotchiDiamond;
s.keyHash = _keyHash; //0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
s.fee = uint96(_fee);
s.aavegotchiDiamond = IAavegotchi(_aavegotchiDiamond);
// adding ERC165 data
s.supportedInterfaces[type(IERC165).interfaceId] = true;
s.supportedInterfaces[type(IERC173).interfaceId] = true;
s.raffles[0].brsMultiplier = 1; //common
s.raffles[1].brsMultiplier = 2; //uncommon
s.raffles[2].brsMultiplier = 5; //rare
s.raffles[3].brsMultiplier = 10; //legendary
s.raffles[4].brsMultiplier = 20; //mythical
s.raffles[5].brsMultiplier = 50; //godlike
for(uint256 i = 0; i < 6; i++){
s.raffles[i].raffleActive = true;
}
}
function supportsInterface(bytes4 _interfaceId) external view override returns (bool) {
return s.supportedInterfaces[_interfaceId];
}
// VRF Functionality ////////////////////////////////////////////////////////////////
function nonces(bytes32 _keyHash) external view returns (uint256 nonce_) {
nonce_ = s.nonces[_keyHash];
}
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev See "SECURITY CONSIDERATIONS" above for more information on _seed.
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to *
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee,
uint256 _seed
) internal returns (bytes32 requestId) {
im_link.transferAndCall(im_vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
// So the seed doesn't actually do anything and is left over from an old API.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), s.nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful Link.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input
// seed, which would result in a predictable/duplicate output.
s.nonces[_keyHash]++;
return makeRequestId(_keyHash, vRFSeed);
}
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
function doNothing() public{
}
function setGhst() public{
ghst = ERC20(0x385Eeac5cB85A38A9a07A70c73e0a3271CfB54A7);
}
function getFeeAmt() public view returns(uint96){
return s.fee;
}
function setFeeAmt(uint96 _newFee) public onlyOwner{
s.fee = _newFee;
}
function withDrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner{
ERC20 token = ERC20(_tokenAddress);
//uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, _amount);
}
function withdrawEntry(uint256 _raffleId) public{
IERC1155 wearables = IERC1155(im_diamondAddress);
//get the item type the entrant entered
uint256 itemId = s.raffles[_raffleId].entrantsMapping[msg.sender];
//send back the wearable the entrant entered
wearables.safeTransferFrom(address(this), msg.sender, itemId, 1, "0x");
//now we need to remove this entrant's info from this raffle
s.raffles[_raffleId].entrantsMapping[msg.sender] = 0;
for(uint i = 0; i < s.raffles[_raffleId].entrants.length; i++){
if(s.raffles[_raffleId].entrants[i] == msg.sender){
//if the entrant was the last entrant, we can just delete him from the array
if(i == s.raffles[_raffleId].entrants.length-1){delete s.raffles[_raffleId].entrants[i];}
//otherwise, deleting him will leave a gap, so we copy in the last entrant to his spot
else{
delete s.raffles[_raffleId].entrants[i];
s.raffles[_raffleId].entrants[i] = s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
delete s.raffles[_raffleId].entrants[s.raffles[_raffleId].entrants.length-1];
}
}
}
}
/*function setRandomNumber(uint256 _raffleId) public onlyOwner {
uint256 raffleId = _raffleId;
require(raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[raffleId];
require(raffle.randomNumber == 0, "Raffle: Random number already generated");
s.raffles[raffleId].randomNumber = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
console.log("Random number is: ", s.raffles[raffleId].randomNumber);
address winner = getWinner(_raffleId);
console.log("Winner should be: ",winner);
raffle.randomNumberPending = false;
}*/
//this returns true if the raffle has surpassed the threshhold number of wearables
//10 for common, 7 for uncommon, 5 for rare, 3 for legendary, 3 for mythical, 2 for godlike
function threshholdReached(uint256 _raffleId) public view returns(bool){
Raffle storage raffle = s.raffles[_raffleId];
if(_raffleId == 0){
return(raffle.entrants.length >= 10);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 7);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 5);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 3);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 3);
}
else if(_raffleId == 0){
return(raffle.entrants.length >= 2);
}
return false;
}
function drawRandomNumber(uint256 _raffleId) public {
//raffle can only be triggered by an authorized user/the owner, OR if the raffle-specific threshhold is reach
require(
isAuthorized[msg.sender] ||
msg.sender == s.contractOwner ||
threshholdReached(_raffleId)
);
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
require(s.raffles[_raffleId].randomNumber == 0, "Raffle: Random number already generated");
require(s.raffles[_raffleId].randomNumberPending == false || msg.sender == s.contractOwner, "Raffle: Random number is pending");
s.raffles[_raffleId].randomNumberPending = true;
// Use Chainlink VRF to generate random number
//require(im_link.balanceOf(address(this)) >= s.fee, "Not enough LINK, need");
bytes32 requestId = requestRandomness(s.keyHash, s.fee, 0);
s.requestIdToRaffleId[requestId] = _raffleId;
s.raffles[_raffleId].raffleActive = false;
}
function getRandomNumber(uint256 _raffleId) public view returns (uint256){
return s.raffles[_raffleId].randomNumber;
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRFproof.
/**
* @notice Callback function used by VRF Coordinator
* @dev This is where you do something with randomness!
* @dev The VRF Coordinator will only send this function verified responses.
* @dev The VRF Coordinator will not pass randomness that could not be verified.
*/
function rawFulfillRandomness(bytes32 _requestId, uint256 _randomness) external {
require(msg.sender == im_vrfCoordinator, "Only VRFCoordinator can fulfill");
uint256 raffleId = s.requestIdToRaffleId[_requestId];
require(raffleId < s.raffles.length, "Raffle: Raffle does not exist");
require(s.raffles[raffleId].randomNumber == 0, "Raffle: Random number already generated");
s.raffles[raffleId].randomNumber = _randomness;
s.raffles[raffleId].randomNumberPending = false;
}
// Change the fee amount that is paid for VRF random numbers
function changeVRFFee(uint256 _newFee, bytes32 _keyHash) external {
require(msg.sender == s.contractOwner, "Raffle: Must be contract owner");
s.fee = uint96(_newFee);
s.keyHash = _keyHash;
}
// Remove the LINK tokens from this contract that are used to pay for VRF random number fees
function removeLinkTokens(address _to, uint256 _value) external {
require(msg.sender == s.contractOwner, "Raffle: Must be contract owner");
im_link.transfer(_to, _value);
}
function linkBalance() external view returns (uint256 linkBalance_) {
linkBalance_ = im_link.balanceOf(address(this));
}
/////////////////////////////////////////////////////////////////////////////////////
function owner() external view override returns (address) {
return s.contractOwner;
}
function transferOwnership(address _newContractOwner) external override {
address previousOwner = s.contractOwner;
require(msg.sender == previousOwner, "Raffle: Must be contract owner");
s.contractOwner = _newContractOwner;
emit OwnershipTransferred(previousOwner, _newContractOwner);
}
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external view returns (bytes4) {
_operator; // silence not used warning
_from; // silence not used warning
_id; // silence not used warning
_value; // silence not used warning
_data;
return ERC1155_ACCEPTED;
}
function returnERC1155(address _tokenAddress,uint256 _id,uint256 _value) public onlyOwner{
IERC1155(_tokenAddress).safeTransferFrom(
address(this),
msg.sender,
_id,
_value,
""
);
}
function resetEntry(address _addy) public onlyOwner{
}
function resetRaffle(uint256 _raffleId) internal {
//add this raffle to the list of historical completed raffles
RaffleLite memory tempEntry;
tempEntry.brsMultiplier = s.raffles[_raffleId].brsMultiplier;
tempEntry.entrants = s.raffles[_raffleId].entrants;
tempEntry.itemsEntered = new uint256[](tempEntry.entrants.length);
for(uint256 i = 0; i<tempEntry.entrants.length; i++){
tempEntry.itemsEntered[i] = s.raffles[_raffleId].entrantsMapping[tempEntry.entrants[i]];
}
tempEntry.randomNumber =s.raffles[_raffleId].randomNumber;
tempEntry.winningIndex = uint256(keccak256(abi.encodePacked(tempEntry.randomNumber, _raffleId))) % tempEntry.entrants.length;
tempEntry.winner = tempEntry.entrants[tempEntry.winningIndex];
tempEntry.blockReset = block.number;
completedRaffles.push(tempEntry);
//check how many entrants there were
uint256 numEntrants = s.raffles[_raffleId].entrants.length;
//go through each one, starting at the end
for(uint256 i = 0; i < numEntrants; i++){
//start at the end of the list, grab the address...
uint256 index = i + 1;
address tempAddy = s.raffles[_raffleId].entrants[numEntrants - index];
//reset the entry to 0
s.raffles[_raffleId].entrantsMapping[tempAddy] = 0;
}
//reset the raffle's random number
s.raffles[_raffleId].randomNumber = 0;
//delete and shrink the array
delete s.raffles[_raffleId].entrants;
//turn the raffle back on
s.raffles[_raffleId].raffleActive = true;
}
function enterWearable(address _tokenAddress, uint256 _id) public{
require(IERC1155(_tokenAddress).balanceOf(msg.sender,_id) > 0, "Insufficient Balance!");
ItemType memory thisItem = s.aavegotchiDiamond.getItemType(_id);
require(thisItem.category == 0, "can only enter wearables");
for(uint256 i = 0; i < s.raffles.length; i++){
if(thisItem.rarityScoreModifier == s.raffles[i].brsMultiplier){
require(s.raffles[i].raffleActive, "raffle not active");
require(s.raffles[i].entrantsMapping[msg.sender] == 0,"already entered in this raffle");
s.raffles[i].entrants.push(msg.sender);
s.raffles[i].entrantsMapping[msg.sender] = _id;
}
}
IERC1155(_tokenAddress).safeTransferFrom(msg.sender,address(this),_id,1,"");
}
function itemBalances(address _account) external view returns (ItemIdIO[] memory bals_) {
return s.aavegotchiDiamond.itemBalances(_account);
}
function isApproved(address _account) public view returns (bool){
IERC1155(im_diamondAddress).isApprovedForAll(_account,address(this));
}
function getEntrants(uint256 _raffleId) public view returns(address[] memory _entrants){
_entrants = s.raffles[_raffleId].entrants;
}
function isWinner(address _address) public view returns(bool){
for(uint256 i = 0; i < 6; i++){
if(getWinner(i) == _address){return true;}
}
}
function getWinningIndex(uint256 _raffleId) public view returns(uint256){
Raffle storage raffle = s.raffles[_raffleId];
uint256 randomNumber = raffle.randomNumber;
//if(randomNumber == 0){return address(0);}
return uint256(
keccak256(abi.encodePacked(randomNumber, _raffleId))
) % raffle.entrants.length;
}
function getAuctionState(uint256 _raffleId) public view returns(uint256){
Raffle storage raffle = s.raffles[_raffleId];
if(raffle.raffleActive == true){
return 0;
}
else if(raffle.randomNumberPending == true){
return 1;
}
else{
return 2;
}
}
function getWinner(uint256 _raffleId) public view returns(address _winner){
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[_raffleId];
//require(raffle.raffleActive == false, "raffle still active");
if(raffle.raffleActive == true){
return address(0);
}
require(raffle.randomNumberPending == false, "waiting on VRF");
uint256 winningIndex = getWinningIndex(_raffleId);
return s.raffles[_raffleId].entrants[winningIndex];
}
function claimAllPrizes(address _entrant) public{
//make sure this entrant has winnings
require(isWinner(_entrant),"Sorry, no prizes for you");
//go through each raffle and collect any winnings
for(uint256 i = 0; i < 6; i++){
Raffle storage raffle = s.raffles[i];
uint256 randomNumber = raffle.randomNumber;
//winner has to have been drawn, function must be called by winner or contract owner, and entrant must be winner
if(
randomNumber > 0 &&
(msg.sender == _entrant || msg.sender == s.contractOwner) &&
getWinner(i) == _entrant
){
//cycle through each entry and send wearable to the winner
for(uint256 j = 0; j<raffle.entrants.length; j++){
uint256 entrantItem = raffle.entrantsMapping[raffle.entrants[j]];
IERC1155(im_diamondAddress).safeTransferFrom(address(this),_entrant,entrantItem,1,"");
}
resetRaffle(i);
if(msg.sender == _entrant){
ghst.transferFrom(msg.sender, address(this), 10000000000000000000);
}
}
}
}
/**
* @notice Claim prizes won
* @dev All items in _wins are verified as actually won by the address that calls this function and reverts otherwise.
* @dev Each entrant address can only claim prizes once, so be sure to include all entries and prizes won.
* @dev Prizes are transfered to the address that calls this function.
* @dev Due to the possibility that an entrant does not claim all the prizes he/she won or the gas cost is too high,
* the contractOwner can claim prizes for an entrant. This needs to be used with care so that contractOwner does not
* accidentally claim prizes for an entrant that have already been claimed for or by the entrant.
* @param _entrant The entrant that won the prizes
* @param _raffleId The raffle that prizes were won in.
*
*/
function claimPrize(
uint256 _raffleId,
address _entrant
) public {
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[_raffleId];
uint256 randomNumber = raffle.randomNumber;
require(randomNumber > 0, "Raffle: Random number not generated yet");
// contractOwner can claim prizes for the entrant. Prizes are only transferred to the entrant
require(msg.sender == _entrant || msg.sender == s.contractOwner, "Raffle: Not claimed by owner or contractOwner");
require(getWinner(_raffleId) == _entrant, "not a winner");
//cycle through each entry and send wearable to the winner
for(uint256 i = 0; i<raffle.entrants.length; i++){
uint256 entrantItem = raffle.entrantsMapping[raffle.entrants[i]];
IERC1155(im_diamondAddress).safeTransferFrom(address(this),_entrant,entrantItem,1,"");
}
resetRaffle(_raffleId);
}
} | require(raffle.raffleActive == false, "raffle still active"); | function getWinner(uint256 _raffleId) public view returns(address _winner){
require(_raffleId < s.raffles.length, "Raffle: Raffle does not exist");
Raffle storage raffle = s.raffles[_raffleId];
if(raffle.raffleActive == true){
return address(0);
}
require(raffle.randomNumberPending == false, "waiting on VRF");
uint256 winningIndex = getWinningIndex(_raffleId);
return s.raffles[_raffleId].entrants[winningIndex];
}
| 14,094,539 |
./partial_match/1/0x000000000000C1CB11D5c062901F32D06248CE48/sources/LiquidGasToken.sol | The amount of tokens in the liquidity pool. This is defined implicitly as the difference between The total supply and the privately owned supply of the token. return The amount of tokens in the liquidity pool. | function poolTokenReserves() external view returns (uint256) {
return _totalMinted.sub(_totalBurned + _ownedSupply);
}
| 2,653,346 |
pragma solidity ^0.6.12;
import './SafeMath.sol';
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
abstract contract ERC20Interface {
function totalSupply() public virtual view returns (uint);
function balanceOf(address tokenOwner) public virtual view returns (uint balance);
function allowance(address tokenOwner, address spender) public virtual view returns (uint remaining);
function transfer(address to, uint tokens) public virtual returns (bool success);
function approve(address spender, uint tokens) public virtual returns (bool success);
function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
abstract contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public virtual;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract TubeToken is ERC20Interface, Owned {
using SafeMath for uint;
address public chief; // the Tube Chief address
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// only cheif contract able to interact the important function !
modifier onlyChief {
require(chief != address(0), 'CHIEF MISSING');
require(msg.sender == chief, 'ACCESS_FORBIDDEN');
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "TUBE2";
name = "TUBE2";
decimals = 18;
_totalSupply = 0 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view override returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Update chief address from chief contract
// ------------------------------------------------------------------------
function updateChief(address _chief) public onlyOwner {
chief = _chief;
}
// ------------------------------------------------------------------------
// Mint token
// ------------------------------------------------------------------------
function mint(address _address, uint amount) public onlyOwner {
_mint(_address, amount);
}
function farmMint(address _address, uint amount) external onlyChief {
_mint(_address, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
balances[account] = balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// ------------------------------------------------------------------------
// Burn token
// ------------------------------------------------------------------------
function burn(address account, uint256 amount) public onlyOwner {
require(account != address(0), "ERC20: burn from the zero address");
require(balances[account] >= amount, "ERC20: burn amount exceeds balance");
balances[account] = balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
fallback() external payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ------------------------------------------------------------------------ Update chief address from chief contract ------------------------------------------------------------------------ | function updateChief(address _chief) public onlyOwner {
chief = _chief;
}
| 14,869,862 |
./full_match/80001/0x5ccdEd3f094A02551e22C2D5d3c3834835942D48/sources/src/LBRouter.sol | Unstuck LBTokens that are sent to this contract by mistake Only callable by the factory owner _lbToken The address of the LBToken _to The address of the user to send back the tokens _ids The list of token ids _amounts The list of amounts to send | function sweepLBToken(
ILBToken _lbToken,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts
) external override onlyFactoryOwner {
_lbToken.safeBatchTransferFrom(address(this), _to, _ids, _amounts);
}
| 9,534,455 |
./full_match/83/0xdb68eC6dFd21791cC9c1f4836b6499e2325461A7/sources/contracts/suErc20Delegator.sol | Sender redeems cTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of cTokens to redeem into underlying return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function redeem(uint256 redeemTokens) external returns (uint256) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature('redeem(uint256)', redeemTokens));
return abi.decode(data, (uint256));
}
| 9,556,318 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
░░░ ░░░ ░░░░░░ ░░░░░░ ░░░░░░ ░░ ░░ ░░░░░░░
▒▒▒▒ ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒
▒▒ ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒
▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓ ▓▓
██ ██ ██████ ██ ██ ██ ██ ██ ███████
https://morphs.wtf
Drifting through the immateria you find a scroll. You sense something
mysterious, cosmic.
You feel compelled to take it. After all, what have you got to lose...
Designed by @polyforms_
https://playgrounds.wtf
https://heyshell.xyz
*/
import "../engines/ShellBaseEngine.sol";
import "../engines/OnChainMetadataEngine.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract MorphsEngine is ShellBaseEngine, OnChainMetadataEngine {
error MintingPeriodHasEnded();
// cant mint after midnight 3/1 CST
uint256 public constant MINTING_ENDS_AT_TIMESTAMP = 1646114400;
function name() external pure returns (string memory) {
return "morphs";
}
function mint(IShellFramework collection, uint256 flag)
external
returns (uint256)
{
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= MINTING_ENDS_AT_TIMESTAMP) {
revert MintingPeriodHasEnded();
}
IntStorage[] memory intData;
// flag is written to token mint data if set
if (flag != 0) {
intData = new IntStorage[](1);
intData[0] = IntStorage({key: "flag", value: flag});
} else {
intData = new IntStorage[](0);
}
uint256 tokenId = collection.mint(
MintEntry({
to: msg.sender,
amount: 1,
options: MintOptions({
storeEngine: false,
storeMintedTo: false,
storeTimestamp: false,
storeBlockNumber: false,
stringData: new StringStorage[](0),
intData: intData
})
})
);
return tokenId;
}
function getPalette(uint256 tokenId) public pure returns (string memory) {
uint256 index = uint256(keccak256(abi.encodePacked(tokenId))) % 6;
return string(abi.encodePacked("P00", Strings.toString(index + 1)));
}
function getVariation(uint256 tokenId, uint256 flag)
public
pure
returns (string memory)
{
if (flag >= 2) {
// celestial
// doing >= 2 to let curious geeks mint things with custom flag
// values.
// I wonder if anybody will do this? 🤔
return "X001";
} else if (flag == 1) {
// mythical
uint256 i = uint256(keccak256(abi.encodePacked(tokenId))) % 4;
return string(abi.encodePacked("M00", Strings.toString(i + 1)));
}
// citizen
uint256 index = uint256(keccak256(abi.encodePacked(tokenId))) % 10;
if (index == 9) {
return "C010"; // double digit case
} else {
return string(abi.encodePacked("C00", Strings.toString(index + 1)));
}
}
function getPaletteName(uint256 tokenId)
public
pure
returns (string memory)
{
uint256 index = uint256(keccak256(abi.encodePacked(tokenId))) % 6;
if (index == 0) {
return "Greyskull";
} else if (index == 1) {
return "Ancient Opinions";
} else if (index == 2) {
return "The Desert Sun";
} else if (index == 3) {
return "The Deep";
} else if (index == 4) {
return "The Jade Prism";
} else if (index == 5) {
return "Cosmic Understanding";
}
return "";
}
function getFlag(IShellFramework collection, uint256 tokenId)
public
view
returns (uint256)
{
return
collection.readTokenInt(StorageLocation.MINT_DATA, tokenId, "flag");
}
function _computeName(IShellFramework collection, uint256 tokenId)
internal
view
override
returns (string memory)
{
uint256 flag = getFlag(collection, tokenId);
return
string(
abi.encodePacked(
"Morph #",
Strings.toString(tokenId),
flag == 2 ? ": Cosmic Scroll of " : flag == 1
? ": Mythical Scroll of "
: ": Scroll of ",
getPaletteName(tokenId)
)
);
}
function _computeDescription(IShellFramework collection, uint256 tokenId)
internal
view
override
returns (string memory)
{
uint256 flag = getFlag(collection, tokenId);
return
string(
abi.encodePacked(
flag > 1
? "A mysterious scroll... you feel it pulsating with cosmic energy. Its whispers speak secrets of cosmic significance."
: flag > 0
? "A mysterious scroll... you feel it pulsating with mythical energy. You sense its power is great."
: "A mysterious scroll... you feel it pulsating with energy. What secrets might it hold?",
"\\n\\nhttps://playgrounds.wtf"
)
);
}
// compute the metadata image field for a given token
function _computeImageUri(IShellFramework collection, uint256 tokenId)
internal
view
override
returns (string memory)
{
uint256 flag = getFlag(collection, tokenId);
string memory image = string(
abi.encodePacked(
"S001-",
getPalette(tokenId),
"-",
getVariation(tokenId, flag),
".png"
)
);
return
string(
abi.encodePacked(
"ipfs://ipfs/QmRCKXGuM47BzepjiHu2onshPFRWb7TMVEfd4K87cszg4w/",
image
)
);
}
// compute the external_url field for a given token
function _computeExternalUrl(IShellFramework, uint256)
internal
pure
override
returns (string memory)
{
return "https://morphs.wtf";
}
function _computeAttributes(IShellFramework collection, uint256 tokenId)
internal
view
override
returns (Attribute[] memory)
{
Attribute[] memory attributes = new Attribute[](3);
attributes[0] = Attribute({
key: "Palette",
value: getPaletteName(tokenId)
});
attributes[1] = Attribute({
key: "Variation",
value: getVariation(tokenId, getFlag(collection, tokenId))
});
uint256 flag = getFlag(collection, tokenId);
attributes[2] = Attribute({
key: "Affinity",
value: flag > 1 ? "Cosmic" : flag > 0 ? "Mythical" : "Citizen"
});
return attributes;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "../IEngine.sol";
// simple starting point for engines
// - default name
// - proper erc165 support
// - no royalties
// - nop on beforeTokenTransfer and afterEngineSet hooks
abstract contract ShellBaseEngine is IEngine {
// nop
function beforeTokenTransfer(
address,
address,
address,
uint256,
uint256
) external pure virtual override {
return;
}
// nop
function afterEngineSet(uint256) external view virtual override {
return;
}
// no royalties
function getRoyaltyInfo(
IShellFramework,
uint256,
uint256
) external view virtual returns (address receiver, uint256 royaltyAmount) {
receiver = address(0);
royaltyAmount = 0;
}
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
override
returns (bool)
{
return
interfaceId == type(IEngine).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../libraries/Base64.sol";
import "../IShellFramework.sol";
import "../IEngine.sol";
struct Attribute {
string key;
string value;
}
abstract contract OnChainMetadataEngine is IEngine {
// Called by the collection to resolve a response for tokenURI
function getTokenURI(IShellFramework collection, uint256 tokenId)
external
view
returns (string memory)
{
string memory name = _computeName(collection, tokenId);
string memory description = _computeDescription(collection, tokenId);
string memory image = _computeImageUri(collection, tokenId);
string memory externalUrl = _computeExternalUrl(collection, tokenId);
Attribute[] memory attributes = _computeAttributes(collection, tokenId);
string memory attributesInnerJson = "";
for (uint256 i = 0; i < attributes.length; i++) {
attributesInnerJson = string(
bytes(
abi.encodePacked(
attributesInnerJson,
i > 0 ? ", " : "",
'{"trait_type": "',
attributes[i].key,
'", "value": "',
attributes[i].value,
'"}'
)
)
);
}
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description":"',
description,
'", "image": "',
image,
'", "external_url": "',
externalUrl,
'", "attributes": [',
attributesInnerJson,
"]}"
)
)
)
)
);
}
// compute the metadata name for a given token
function _computeName(IShellFramework collection, uint256 tokenId)
internal
view
virtual
returns (string memory);
// compute the metadata description for a given token
function _computeDescription(IShellFramework collection, uint256 tokenId)
internal
view
virtual
returns (string memory);
// compute the metadata image field for a given token
function _computeImageUri(IShellFramework collection, uint256 tokenId)
internal
view
virtual
returns (string memory);
// compute the external_url field for a given token
function _computeExternalUrl(IShellFramework collection, uint256 tokenId)
internal
view
virtual
returns (string memory);
function _computeAttributes(IShellFramework collection, uint256 token)
internal
view
virtual
returns (Attribute[] memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "./IShellFramework.sol";
// Required interface for framework engines
// interfaceId = 0x0b1d171c
interface IEngine is IERC165 {
// Get the name for this engine
function name() external pure returns (string memory);
// Called by the framework to resolve a response for tokenURI method
function getTokenURI(IShellFramework collection, uint256 tokenId)
external
view
returns (string memory);
// Called by the framework to resolve a response for royaltyInfo method
function getRoyaltyInfo(
IShellFramework collection,
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
// Called by the framework during a transfer, including mints (from=0) and
// burns (to=0). Cannot break transfer even in the case of reverting, as the
// collection will wrap the downstream call in a try/catch
// collection = msg.sender
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256 tokenId,
uint256 amount
) external;
// Called by the framework whenever an engine is set on a fork, including
// the collection (fork id = 0). Can be used by engine developers to prevent
// an engine from being installed in a collection or non-canonical fork if
// desired
// collection = msg.sender
function afterEngineSet(uint256 forkId) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./libraries/IOwnable.sol";
import "./IEngine.sol";
// storage flag
enum StorageLocation {
INVALID,
// set by the engine at any time, mutable
ENGINE,
// set by the engine during minting, immutable
MINT_DATA,
// set by the framework during minting or collection creation, immutable
FRAMEWORK
}
// string key / value
struct StringStorage {
string key;
string value;
}
// int key / value
struct IntStorage {
string key;
uint256 value;
}
// data provided when minting a new token
struct MintEntry {
address to;
uint256 amount;
MintOptions options;
}
// Data provided by engine when minting a new token
struct MintOptions {
bool storeEngine;
bool storeMintedTo;
bool storeTimestamp;
bool storeBlockNumber;
StringStorage[] stringData;
IntStorage[] intData;
}
// Information about a fork
struct Fork {
IEngine engine;
address owner;
}
// Interface for every collection launched by shell.
// Concrete implementations must return true on ERC165 checks for this interface
// (as well as erc165 / 2981)
// interfaceId = TBD
interface IShellFramework is IERC165, IERC2981 {
// ---
// Framework errors
// ---
// an engine was provided that did no pass the expected erc165 checks
error InvalidEngine();
// a write was attempted that is not allowed
error WriteNotAllowed();
// an operation was attempted but msg.sender was not the expected engine
error SenderNotEngine();
// an operation was attempted but msg.sender was not the fork owner
error SenderNotForkOwner();
// a token fork was attempted by an invalid msg.sender
error SenderCannotFork();
// ---
// Framework events
// ---
// a fork was created
event ForkCreated(uint256 forkId, IEngine engine, address owner);
// a fork had a new engine installed
event ForkEngineUpdated(uint256 forkId, IEngine engine);
// a fork had a new owner set
event ForkOwnerUpdated(uint256 forkId, address owner);
// a token has been set to a new fork
event TokenForkUpdated(uint256 tokenId, uint256 forkId);
// ---
// Storage events
// ---
// A fork string was stored
event ForkStringUpdated(
StorageLocation location,
uint256 forkId,
string key,
string value
);
// A fork int was stored
event ForkIntUpdated(
StorageLocation location,
uint256 forkId,
string key,
uint256 value
);
// A token string was stored
event TokenStringUpdated(
StorageLocation location,
uint256 tokenId,
string key,
string value
);
// A token int was stored
event TokenIntUpdated(
StorageLocation location,
uint256 tokenId,
string key,
uint256 value
);
// ---
// Collection base
// ---
// called immediately after cloning
function initialize(
string calldata name,
string calldata symbol,
IEngine engine,
address owner
) external;
// ---
// General collection info / metadata
// ---
// collection owner (fork 0 owner)
function owner() external view returns (address);
// collection name
function name() external view returns (string memory);
// collection name
function symbol() external view returns (string memory);
// next token id serial number
function nextTokenId() external view returns (uint256);
// next fork id serial number
function nextForkId() external view returns (uint256);
// ---
// Fork functionality
// ---
// Create a new fork with a specific engine, fork all the tokenIds to the
// new engine, and return the fork ID
function createFork(
IEngine engine,
address owner,
uint256[] calldata tokenIds
) external returns (uint256);
// Set the engine for a specific fork. Must be fork owner
function setForkEngine(uint256 forkId, IEngine engine) external;
// Set the fork owner. Must be fork owner
function setForkOwner(uint256 forkId, address owner) external;
// Set the fork of a specific token. Must be token owner
function setTokenFork(uint256 tokenId, uint256 forkId) external;
// Set the fork for several tokens. Must own all tokens
function setTokenForks(uint256[] memory tokenIds, uint256 forkId) external;
// ---
// Fork views
// ---
// Get information about a fork
function getFork(uint256 forkId) external view returns (Fork memory);
// Get the collection / canonical engine. getFork(0).engine
function getForkEngine(uint256 forkId) external view returns (IEngine);
// Get a token's fork ID
function getTokenForkId(uint256 tokenId) external view returns (uint256);
// Get a token's engine. getFork(getTokenForkId(tokenId)).engine
function getTokenEngine(uint256 tokenId) external view returns (IEngine);
// Determine if a given msg.sender can fork a token
function canSenderForkToken(address sender, uint256 tokenId)
external
view
returns (bool);
// ---
// Engine functionality
// ---
// mint new tokens. Only callable by collection engine
function mint(MintEntry calldata entry) external returns (uint256);
// mint new tokens. Only callable by collection engine
function batchMint(MintEntry[] calldata entries)
external
returns (uint256[] memory);
// ---
// Storage writes
// ---
// Write a string to collection storage. Only callable by collection engine
function writeForkString(
StorageLocation location,
uint256 forkId,
string calldata key,
string calldata value
) external;
// Write a string to collection storage. Only callable by collection engine
function writeForkInt(
StorageLocation location,
uint256 forkId,
string calldata key,
uint256 value
) external;
// Write a string to token storage. Only callable by token engine
function writeTokenString(
StorageLocation location,
uint256 tokenId,
string calldata key,
string calldata value
) external;
// Write a string to token storage. Only callable by token engine
function writeTokenInt(
StorageLocation location,
uint256 tokenId,
string calldata key,
uint256 value
) external;
// ---
// Storage reads
// ---
// Read a string from collection storage
function readForkString(
StorageLocation location,
uint256 forkId,
string calldata key
) external view returns (string memory);
// Read a uint256 from collection storage
function readForkInt(
StorageLocation location,
uint256 forkId,
string calldata key
) external view returns (uint256);
// Read a string from token storage
function readTokenString(
StorageLocation location,
uint256 tokenId,
string calldata key
) external view returns (string memory);
// Read a uint256 from token storage
function readTokenInt(
StorageLocation location,
uint256 tokenId,
string calldata key
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// (semi) standard ownable interface
interface IOwnable {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// https://github.com/Brechtpd/base64/blob/main/base64.sol
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
} | Required interface for framework engines interfaceId = 0x0b1d171c Get the name for this engine Called by the framework to resolve a response for tokenURI method Called by the framework to resolve a response for royaltyInfo method Called by the framework during a transfer, including mints (from=0) and burns (to=0). Cannot break transfer even in the case of reverting, as the collection will wrap the downstream call in a try/catch collection = msg.sender Called by the framework whenever an engine is set on a fork, including the collection (fork id = 0). Can be used by engine developers to prevent an engine from being installed in a collection or non-canonical fork if desired collection = msg.sender | interface IEngine is IERC165 {
function name() external pure returns (string memory);
function getTokenURI(IShellFramework collection, uint256 tokenId)
external
view
returns (string memory);
function getRoyaltyInfo(
IShellFramework collection,
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256 tokenId,
uint256 amount
) external;
function afterEngineSet(uint256 forkId) external;
pragma solidity ^0.8.0;
}
| 14,570,659 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./SLNToken.sol";
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SLNToken is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract StarPoolsV2 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardRemain; // Remain rewards
//
// We do some fancy math here. Basically, any point in time, the amount of SLNTokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRewardPerShare) + user.rewardRemain - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User calc the pending rewards and record at rewardRemain.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SLNTokens to distribute per block.
uint256 lastRewardBlock; // Last block number that SLNTokens distribution occurs.
uint256 accRewardPerShare; // Accumulated SLNTokens per share, times 1e18. See below.
uint256 totalAmount; // Total amount of current pool deposit.
uint256 pooltype; // pool type, 1 = Single ERC20 or 2 = LP Token or 3 = nft Pool
}
// The SLN TOKEN!
SLNToken public slnToken;
// Dev address.
address public devaddr;
// Operater address.
address public opeaddr;
// SLN tokens created per block.
uint256 public rewardPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// the SLN tokens distribution
uint256 public rewardDistributionFactor = 1e9;
// The block number when SLN Token mining starts.
uint256 public startBlock;
// Reduction
uint256 public reductionBlockPeriod; // 60/3*60*24*7 = 201600
uint256 public maxReductionCount;
uint256 public nextReductionBlock;
uint256 public reductionCounter;
// Block number when bonus SLN reduction period ends.
uint256 public bonusStableBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Claim(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor (
SLNToken _slnToken,
address _devaddr,
address _opeaddr,
uint256 _rewardPerBlock,
uint256 _startBlock
) public {
slnToken = _slnToken;
devaddr = _devaddr;
opeaddr = _opeaddr;
startBlock = _startBlock;
rewardPerBlock = _rewardPerBlock;
reductionBlockPeriod = 201600; // 60/3*60*24*7 = 201600
maxReductionCount = 12;
bonusStableBlock = _startBlock.add(reductionBlockPeriod.mul(maxReductionCount));
nextReductionBlock = _startBlock.add(reductionBlockPeriod);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _pooltype) public onlyOwner {
massUpdatePools();
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0,
totalAmount: 0,
pooltype: _pooltype
}));
}
// Set the number of sln produced by each block
function setRewardPerBlock(uint256 _newPerBlock) external onlyOwner {
massUpdatePools();
rewardPerBlock = _newPerBlock;
}
function setRewardDistributionFactor(uint256 _rewardDistributionFactor) external onlyOwner {
massUpdatePools();
rewardDistributionFactor = _rewardDistributionFactor;
}
// Update the given pool's SLNToken allocation point. Can only be called by the owner.
function setAllocPoint(uint256 _pid, uint256 _allocPoint) external onlyOwner {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Pooltype to set pool display type on frontend.
function setPoolType(uint256 _pid, uint256 _pooltype) external onlyOwner {
poolInfo[_pid].pooltype = _pooltype;
}
function setReductionArgs(uint256 _reductionBlockPeriod, uint256 _maxReductionCount) external onlyOwner {
nextReductionBlock = nextReductionBlock.sub(reductionBlockPeriod).add(_reductionBlockPeriod);
bonusStableBlock = nextReductionBlock.add(_reductionBlockPeriod.mul(_maxReductionCount.sub(reductionCounter).sub(1)));
reductionBlockPeriod = _reductionBlockPeriod;
maxReductionCount = _maxReductionCount;
}
// Return reward multiplier over the given _from to _to block.
function getBlocksReward(uint256 _from, uint256 _to) public view returns (uint256 value) {
uint256 prevReductionBlock = nextReductionBlock.sub(reductionBlockPeriod);
if ((_from >= prevReductionBlock && _to <= nextReductionBlock) ||
(_from > bonusStableBlock))
{
value = getBlockReward(_to.sub(_from), rewardPerBlock, reductionCounter);
}
else if (_from < prevReductionBlock && _to < nextReductionBlock)
{
uint256 part1 = getBlockReward(_to.sub(prevReductionBlock), rewardPerBlock, reductionCounter);
uint256 part2 = getBlockReward(prevReductionBlock.sub(_from), rewardPerBlock, reductionCounter.sub(1));
value = part1.add(part2);
}
else // if (_from > prevReductionBlock && _to > nextReductionBlock)
{
uint256 part1 = getBlockReward(_to.sub(nextReductionBlock), rewardPerBlock, reductionCounter.add(1));
uint256 part2 = getBlockReward(nextReductionBlock.sub(_from), rewardPerBlock, reductionCounter);
value = part1.add(part2);
}
value = value.mul(rewardDistributionFactor).div(1e9);
}
// Return reward per block
function getBlockReward(uint256 _blockCount, uint256 _rewardPerBlock, uint256 _reductionCounter) internal view returns (uint256) {
uint256 reward = _blockCount.mul(_rewardPerBlock);
if (_reductionCounter == 0) {
return reward;
}else if (_reductionCounter >= maxReductionCount) {
return reward.mul(6).div(100);
}
// _reductionCounter no more than maxReductionCount (12)
return reward.mul(80 ** _reductionCounter).div(100 ** _reductionCounter);
}
// View function to see pending SLNTokens on frontend.
function pendingRewards(uint256 _pid, address _user) public view returns (uint256 value) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
value = totalRewards(pool, user).add(user.rewardRemain).sub(user.rewardDebt);
}
function totalRewards(PoolInfo memory _pool, UserInfo memory _user) internal view returns (uint256 value) {
uint256 accRewardPerShare = _pool.accRewardPerShare;
if (block.number > _pool.lastRewardBlock && _pool.totalAmount != 0) {
uint256 blockReward = getBlocksReward(_pool.lastRewardBlock, block.number);
uint256 poolReward = blockReward.mul(_pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e18).div(_pool.totalAmount));
}
value = _user.amount.mul(accRewardPerShare).div(1e18);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.allocPoint == 0) {
return;
}
if (block.number > nextReductionBlock) {
if(reductionCounter >= maxReductionCount) {
bonusStableBlock = nextReductionBlock;
}else{
nextReductionBlock = nextReductionBlock.add(reductionBlockPeriod);
reductionCounter = reductionCounter.add(1);
}
}
if (pool.totalAmount == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockReward = getBlocksReward(pool.lastRewardBlock, block.number);
uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint);
if(poolReward > 0) {
// 9699%% for pools = 8999/9699 for pool miner, 500/9699 for team and 200/9699 for business
slnToken.mint(devaddr, poolReward.mul(500).div(8999));
slnToken.mint(opeaddr, poolReward.mul(200).div(8999));
slnToken.mint(address(this), poolReward);
}
pool.accRewardPerShare = pool.accRewardPerShare.add(poolReward.mul(1e18).div(pool.totalAmount));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SLNToken allocation.
function deposit(uint256 _pid, uint256 _amount) external {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
user.rewardRemain = pendingRewards(_pid, msg.sender);
// user.rewardDebt = 0;
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
pool.totalAmount = pool.totalAmount.add(_amount);
}
user.rewardDebt = totalRewards(pool, user);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StarPool.
function withdraw(uint256 _pid, uint256 _amount) external {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
user.rewardRemain = pendingRewards(_pid, msg.sender);
user.rewardDebt = 0;
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalAmount = pool.totalAmount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = totalRewards(pool, user);
emit Withdraw(msg.sender, _pid, _amount);
}
function claimAll(uint256 _pid) external returns(uint256 value) {
updatePool(_pid);
value = pendingRewards(_pid, msg.sender);
// require(value >= 0, "claim: not good");
if (value > 0) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
user.rewardRemain = 0;
safeSlnTransfer(msg.sender, value);
user.rewardDebt = totalRewards(pool, user);
}
emit Claim(msg.sender, _pid, value);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
// user.rewardDebt = 0;
// user.rewardRemain = 0;
pool.totalAmount = pool.totalAmount.sub(amount);
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe SLNToken transfer function, just in case if rounding error causes pool to not have enough SLNTokens.
function safeSlnTransfer(address _to, uint256 _amount) internal {
uint256 slnBalance = slnToken.balanceOf(address(this));
if (_amount > slnBalance) {
slnToken.transfer(_to, slnBalance);
} else {
slnToken.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) external {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Update ope address by the previous ope.
function ope(address _opeaddr) external {
require(msg.sender == opeaddr, "ope: wut?");
opeaddr = _opeaddr;
}
// If the user transfers TH to contract, it will revert
receive() external payable {
revert();
}
}
| Pooltype to set pool display type on frontend. | function setPoolType(uint256 _pid, uint256 _pooltype) external onlyOwner {
poolInfo[_pid].pooltype = _pooltype;
}
| 15,872,868 |
pragma solidity ^0.4.24;
// File: contracts/libs/PointsCalculator.sol
library PointsCalculator {
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
struct MatchResult{
uint8 result; /* 0-> draw, 1-> won 1, 2-> won 2 */
uint8 under49;
uint8 touchdowns;
}
struct Extras {
uint16 interceptions;
uint16 missedFieldGoals;
uint16 overtimes;
uint16 sacks;
uint16 fieldGoals;
uint16 fumbles;
}
struct BonusMatch {
uint16 bonus;
}
/**
* @notice get points from a single match
* @param matchIndex index of the match
* @param matches token predictions
* @return
*/
function getMatchPoints (uint256 matchIndex, uint160 matches, MatchResult[] matchResults, bool[] starMatches) private pure returns(uint16 matchPoints) {
uint8 tResult = uint8(matches & MATCH_RESULT_MASK);
uint8 tUnder49 = uint8((matches >> 2) & MATCH_UNDEROVER_MASK);
uint8 tTouchdowns = uint8((matches >> 3) & MATCH_TOUCHDOWNS_MASK);
uint8 rResult = matchResults[matchIndex].result;
uint8 rUnder49 = matchResults[matchIndex].under49;
uint8 rTouchdowns = matchResults[matchIndex].touchdowns;
if (rResult == tResult) {
matchPoints += 5;
if(rResult == 0) {
matchPoints += 5;
}
if(starMatches[matchIndex]) {
matchPoints += 2;
}
}
if(tUnder49 == rUnder49) {
matchPoints += 1;
}
if(tTouchdowns == rTouchdowns) {
matchPoints += 4;
}
}
/**
* @notice calculates points won by yellow and red cards predictions
* @param extras token predictions
* @return amount of points
*/
function getExtraPoints(uint96 extras, Extras extraStats) private pure returns(uint16 extraPoints){
uint16 interceptions = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 missedFieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 overtimes = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 sacks = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fieldGoals = uint16(extras & EXTRA_STATS_MASK);
extras = extras >> 16;
uint16 fumbles = uint16(extras & EXTRA_STATS_MASK);
if (interceptions == extraStats.interceptions){
extraPoints += 6;
}
if (missedFieldGoals == extraStats.missedFieldGoals){
extraPoints += 6;
}
if (overtimes == extraStats.overtimes){
extraPoints += 6;
}
if (sacks == extraStats.sacks){
extraPoints += 6;
}
if (fieldGoals == extraStats.fieldGoals){
extraPoints += 6;
}
if (fumbles == extraStats.fumbles){
extraPoints += 6;
}
}
/**
*
*
*
*/
function getBonusPoints (uint256 bonusId, uint32 bonuses, BonusMatch[] bonusMatches) private pure returns(uint16 bonusPoints) {
uint8 bonus = uint8(bonuses & BONUS_STAT_MASK);
if(bonusMatches[bonusId].bonus == bonus) {
bonusPoints += 2;
}
}
function calculateTokenPoints (uint160 tMatchResults, uint32 tBonusMatches, uint96 tExtraStats, MatchResult[] storage matchResults, Extras storage extraStats, BonusMatch[] storage bonusMatches, bool[] starMatches)
external pure returns(uint16 points){
//Matches
uint160 m = tMatchResults;
for (uint256 i = 0; i < MATCHES_NUMBER; i++){
points += getMatchPoints(MATCHES_NUMBER - i - 1, m, matchResults, starMatches);
m = m >> 8;
}
//BonusMatches
uint32 b = tBonusMatches;
for(uint256 j = 0; j < BONUS_MATCHES; j++) {
points += getBonusPoints(BONUS_MATCHES - j - 1, b, bonusMatches);
b = b >> 6;
}
//Extras
points += getExtraPoints(tExtraStats, extraStats);
}
}
// File: contracts/dataSource/DataSourceInterface.sol
contract DataSourceInterface {
function isDataSource() public pure returns (bool);
function getMatchResults() external;
function getExtraStats() external;
function getBonusResults() external;
}
// File: contracts/game/GameStorage.sol
// Matches
// 0 Baltimore,Cleveland Bonus
// 1 Denver,New York Bonus
// 2 Atlanta,Pittsburgh
// 3 New York,Carolina
// 4 Minnesota,Philadelphia Bonus
// 5 Arizona,San Francisco
// 6 Los Angeles,Seattle
// 7 Dallas,Houston Star
contract GameStorage{
event LogTokenBuilt(address creatorAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogTokenGift(address creatorAddress, address giftedAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
event LogPrepaidTokenBuilt(address creatorAddress, bytes32 secret);
event LogPrepaidRedeemed(address redeemer, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b);
uint256 constant STARTING_PRICE = 50 finney;
uint256 constant FIRST_PHASE = 1540393200;
uint256 constant EVENT_START = 1541084400;
uint8 constant MATCHES_NUMBER = 20;
uint8 constant BONUS_MATCHES = 5;
//6, 12, 18
bool[] internal starMatches = [false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, true, false];
uint16 constant EXTRA_STATS_MASK = 65535;
uint8 constant MATCH_UNDEROVER_MASK = 1;
uint8 constant MATCH_RESULT_MASK = 3;
uint8 constant MATCH_TOUCHDOWNS_MASK = 31;
uint8 constant BONUS_STAT_MASK = 63;
uint256 public prizePool = 0;
uint256 public adminPool = 0;
mapping (uint256 => uint16) public tokenToPointsMap;
mapping (uint256 => uint256) public tokenToPayoutMap;
mapping (bytes32 => uint8) public secretsMap;
address public dataSourceAddress;
DataSourceInterface internal dataSource;
enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished }
pointsValidationState public pValidationState = pointsValidationState.Unstarted;
uint256 internal pointsLimit = 0;
uint32 internal lastCalculatedToken = 0;
uint32 internal lastCheckedToken = 0;
uint32 internal winnerCounter = 0;
uint32 internal lastAssigned = 0;
uint32 internal payoutRange = 0;
uint32 internal lastPrizeGiven = 0;
uint16 internal superiorQuota;
uint16[] internal payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500];
uint24[21] internal payoutDistribution;
uint256[] internal sortedWinners;
PointsCalculator.MatchResult[] public matchResults;
PointsCalculator.BonusMatch[] public bonusMatches;
PointsCalculator.Extras public extraStats;
}
// File: contracts/CryptocupStorage.sol
contract CryptocupStorage is GameStorage {
}
// File: contracts/ticket/TicketInterface.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface TicketInterface {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function getOwnedTokens(address _from) public view returns(uint256[]);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public;
}
// File: contracts/ticket/TicketStorage.sol
contract TicketStorage is TicketInterface{
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
struct Token {
uint160 matches;
uint32 bonusMatches;
uint96 extraStats;
uint64 timeStamp;
string message;
}
// List of all tokens
Token[] tokens;
mapping (uint256 => address) public tokenOwner;
mapping (uint256 => address) public tokenApprovals;
mapping (address => uint256[]) internal ownedTokens;
mapping (address => mapping (address => bool)) public operatorApprovals;
}
// File: contracts/libs/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/helpers/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/access/AccessStorage.sol
contract AccessStorage{
bool public paused = false;
bool public finalized = false;
address public adminAddress;
address public dataSourceAddress;
address public marketplaceAddress;
uint256 internal deploymentTime = 0;
uint256 public gameFinishedTime = 0;
uint256 public finalizedTime = 0;
}
// File: contracts/access/AccessRegistry.sol
/**
* @title AccessControlLayer
* @author CryptoCup Team (https://cryptocup.io/about)
* @dev Containes basic admin modifiers to restrict access to some functions. Allows
* for pauseing, and setting emergency stops.
*/
contract AccessRegistry is AccessStorage {
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyAdmin() {
require(msg.sender == adminAddress, "Only admin.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyDataSource() {
require(msg.sender == dataSourceAddress, "Only dataSource.");
_;
}
/**
* @dev Main modifier to limit access to delicate functions.
*/
modifier onlyMarketPlace() {
require(msg.sender == marketplaceAddress, "Only marketplace.");
_;
}
/**
* @dev Modifier that checks that the contract is not paused
*/
modifier isNotPaused() {
require(!paused, "Only if not paused.");
_;
}
/**
* @dev Modifier that checks that the contract is paused
*/
modifier isPaused() {
require(paused, "Only if paused.");
_;
}
/**
* @dev Modifier that checks that the contract has finished successfully
*/
modifier hasFinished() {
require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)), "Only if game has finished.");
_;
}
/**
* @dev Modifier that checks that the contract has finalized
*/
modifier hasFinalized() {
require(finalized, "Only if game has finalized.");
_;
}
function setPause () internal {
paused = true;
}
function unSetPause() internal {
paused = false;
}
/**
* @dev Transfer contract's ownership
* @param _newAdmin Address to be set
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
/**
* @dev Adds contract's mkt
* @param _newMkt Address to be set
*/
function setMarketplaceAddress(address _newMkt) external onlyAdmin {
require(_newMkt != address(0));
marketplaceAddress = _newMkt;
}
/**
* @dev Sets the contract pause state
* @param state True to pause
*/
function setPauseState(bool state) external onlyAdmin {
paused = state;
}
/**
* @dev Sets the contract to finalized
* @param state True to finalize
*/
function setFinalized(bool state) external onlyAdmin {
paused = state;
finalized = state;
if(finalized == true)
finalizedTime = now;
}
}
// File: contracts/ticket/TicketRegistry.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract TicketRegistry is TicketInterface, TicketStorage, AccessRegistry{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Gets tokens of owner
* @param _from address of the owner
* @return array with token ids
*/
function getOwnedTokens(address _from) public view returns(uint256[]) {
return ownedTokens[_from];
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public isNotPaused{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require (_from != _to);
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public {
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
// require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool){
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
//emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokens[_to].push(_tokenId);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
require(ownedTokens[_from].length < 100);
tokenOwner[_tokenId] = address(0);
uint256[] storage tokenArray = ownedTokens[_from];
for (uint256 i = 0; i < tokenArray.length; i++){
if(tokenArray[i] == _tokenId){
tokenArray[i] = tokenArray[tokenArray.length-1];
}
}
delete tokenArray[tokenArray.length-1];
tokenArray.length--;
}
}
// File: contracts/libs/PayoutDistribution.sol
library PayoutDistribution {
function getDistribution(uint256 tokenCount) external pure returns (uint24[21] payoutDistribution) {
if(tokenCount < 101){
payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 201){
payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 301){
payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 501){
payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 1001){
payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0];
}else if(tokenCount < 2001){
payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0];
}else if(tokenCount < 3001){
payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0];
}else if(tokenCount < 5001){
payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0];
}else if(tokenCount < 10001){
payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0];
}else if(tokenCount < 25001){
payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0];
} else {
payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70];
}
}
function getSuperiorQuota(uint256 tokenCount) external pure returns (uint16 superiorQuota){
if(tokenCount < 101){
superiorQuota = 10;
}else if(tokenCount < 201){
superiorQuota = 20;
}else if(tokenCount < 301){
superiorQuota = 30;
}else if(tokenCount < 501){
superiorQuota = 50;
}else if(tokenCount < 1001){
superiorQuota = 100;
}else if(tokenCount < 2001){
superiorQuota = 200;
}else if(tokenCount < 3001){
superiorQuota = 300;
}else if(tokenCount < 5001){
superiorQuota = 500;
}else if(tokenCount < 10001){
superiorQuota = 1000;
}else if(tokenCount < 25001){
superiorQuota = 2500;
} else {
superiorQuota = 5000;
}
}
}
// File: contracts/game/GameRegistry.sol
contract GameRegistry is CryptocupStorage, TicketRegistry{
using PointsCalculator for PointsCalculator.MatchResult;
using PointsCalculator for PointsCalculator.BonusMatch;
using PointsCalculator for PointsCalculator.Extras;
/**
* @dev Checks if pValidationState is in the provided stats
* @param state State required to run
*/
modifier checkState(pointsValidationState state){
require(pValidationState == state, "Points validation stage invalid.");
_;
}
/**
* @notice Gets current token price
*/
function _getTokenPrice() internal view returns(uint256 tokenPrice){
if (now >= FIRST_PHASE) {
tokenPrice = (80 finney);
} else {
tokenPrice = STARTING_PRICE;
}
require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney));
}
function _prepareMatchResultsArray() internal {
matchResults.length = MATCHES_NUMBER;
}
function _prepareBonusResultsArray() internal {
bonusMatches.length = BONUS_MATCHES;
}
/**
* @notice Builds ERC721 token with the predictions provided by the user.
* @param matches - Matches results (who wins, amount of points)
* @param bonusMatches - Stats from bonus matches
* @param extraStats - Total number of extra stats like touchdonws, etc.
* @dev An automatic timestamp is added for internal use.
*/
function _createToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string userMessage) internal returns (uint256){
Token memory token = Token({
matches: matches,
bonusMatches: bonusMatches,
extraStats: extraStats,
timeStamp: uint64(now),
message: userMessage
});
uint256 tokenId = tokens.push(token) - 1;
require(tokenId == uint256(uint32(tokenId)), "Failed to convert tokenId to uint256.");
return tokenId;
}
/**
* @dev Sets the data source contract address
* @param _address Address to be set
*/
function setDataSourceAddress(address _address) external onlyAdmin {
DataSourceInterface c = DataSourceInterface(_address);
require(c.isDataSource());
dataSource = c;
dataSourceAddress = _address;
}
/**
* @notice Called by the development team once the World Cup has ended (adminPool is set)
* @dev Allows dev team to retrieve adminPool
*/
function adminWithdrawBalance() external onlyAdmin {
uint256 adminPrize = adminPool;
adminPool = 0;
adminAddress.transfer(adminPrize);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function finishedGameWithdraw() external onlyAdmin hasFinished{
uint256 balance = address(this).balance;
adminAddress.transfer(balance);
}
/**
* @notice Let the admin cash-out the entire contract balance 10 days after game has finished.
*/
function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{
require(finalizedTime != 0 && now >= finalizedTime + 10 days );
msg.sender.transfer(address(this).balance);
}
function isDataSourceCallback() external pure returns (bool){
return true;
}
function dataSourceGetMatchesResults() external onlyAdmin {
dataSource.getMatchResults();
}
function dataSourceGetBonusResults() external onlyAdmin{
dataSource.getBonusResults();
}
function dataSourceGetExtraStats() external onlyAdmin{
dataSource.getExtraStats();
}
function dataSourceCallbackMatch(uint160 matches) external onlyDataSource{
uint160 m = matches;
for(uint256 i = 0; i < MATCHES_NUMBER; i++) {
matchResults[MATCHES_NUMBER - i - 1].result = uint8(m & MATCH_RESULT_MASK);
matchResults[MATCHES_NUMBER - i - 1].under49 = uint8((m >> 2) & MATCH_UNDEROVER_MASK);
matchResults[MATCHES_NUMBER - i - 1].touchdowns = uint8((m >> 3) & MATCH_TOUCHDOWNS_MASK);
m = m >> 8;
}
}
function dataSourceCallbackBonus(uint32 bonusResults) external onlyDataSource{
uint32 b = bonusResults;
for(uint256 i = 0; i < BONUS_MATCHES; i++) {
bonusMatches[BONUS_MATCHES - i - 1].bonus = uint8(b & BONUS_STAT_MASK);
b = b >> 6;
}
}
function dataSourceCallbackExtras(uint96 es) external onlyDataSource{
uint96 e = es;
extraStats.interceptions = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.missedFieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.overtimes = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.sacks = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fieldGoals = uint16(e & EXTRA_STATS_MASK);
e = e >> 16;
extraStats.fumbles = uint16(e & EXTRA_STATS_MASK);
}
/**
* @notice Sets the points of all the tokens between the last chunk set and the amount given.
* @dev This function uses all the data collected earlier by oraclize to calculate points.
* @param amount The amount of tokens that should be analyzed.
*/
function calculatePointsBlock(uint32 amount) external{
require (gameFinishedTime == 0);
require(amount + lastCheckedToken <= tokens.length);
for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) {
uint16 points = PointsCalculator.calculateTokenPoints(tokens[i].matches, tokens[i].bonusMatches,
tokens[i].extraStats, matchResults, extraStats, bonusMatches, starMatches);
tokenToPointsMap[i] = points;
}
lastCalculatedToken += amount;
}
/**
* @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the
* percentage of the pot each position gets, last position is the percentage of the pot the last position gets,
* and superior quota is the total amount OF winners that are given a prize.
* @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game
*/
function setPayoutDistributionId () internal {
uint24[21] memory auxArr = PayoutDistribution.getDistribution(tokens.length);
for(uint256 i = 0; i < auxArr.length; i++){
payoutDistribution[i] = auxArr[i];
}
superiorQuota = PayoutDistribution.getSuperiorQuota(tokens.length);
}
/**
* @notice Sets the id of the last token that will be given a prize.
* @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts
* needed to just the winners and not the whole array of tokens.
* @param tokenId last token id
*/
function setLimit(uint256 tokenId) external onlyAdmin{
require(tokenId < tokens.length);
require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet);
pointsLimit = tokenId;
pValidationState = pointsValidationState.LimitSet;
lastCheckedToken = 0;
lastCalculatedToken = 0;
winnerCounter = 0;
setPause();
setPayoutDistributionId();
}
/**
* @notice Sets the 10th percentile of the sorted array of points
* @param amount tokens in a chunk
*/
function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){
require(amount + lastCheckedToken <= tokens.length);
uint256 points = tokenToPointsMap[pointsLimit];
for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){
if(tokenToPointsMap[i] > points ||
(tokenToPointsMap[i] == points && i <= pointsLimit)){
winnerCounter++;
}
}
lastCheckedToken += amount;
if(lastCheckedToken == tokens.length){
require(superiorQuota == winnerCounter);
pValidationState = pointsValidationState.LimitCalculated;
}
}
/**
* @notice Checks if the order given offchain coincides with the order of the actual previously calculated points
* in the smart contract.
* @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that
* could occur from doing all the sorting onchain.
* @param sortedChunk chunk sorted by points
*/
function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
require(sortedChunk.length + sortedWinners.length <= winnerCounter);
for(uint256 i = 0; i < sortedChunk.length - 1; i++){
uint256 id = sortedChunk[i];
uint256 sigId = sortedChunk[i+1];
require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] &&
id < sigId));
}
if(sortedWinners.length != 0){
uint256 id2 = sortedWinners[sortedWinners.length-1];
uint256 sigId2 = sortedChunk[0];
require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] ||
(tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2));
}
for(uint256 j = 0; j < sortedChunk.length; j++){
sortedWinners.push(sortedChunk[j]);
}
if(sortedWinners.length == winnerCounter){
require(sortedWinners[sortedWinners.length-1] == pointsLimit);
pValidationState = pointsValidationState.OrderChecked;
}
}
/**
* @notice If anything during the point calculation and sorting part should fail, this function can reset
* data structures to their initial position, so as to
*/
function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){
sortedWinners.length = newLength;
}
/**
* @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside
* tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens
* tie inside of the first 30 tokens, the prize will be summed and divided equally.
*/
function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){
uint256 percent = 0;
uint[] memory tokensEquals = new uint[](30);
uint16 tokenEqualsCounter = 0;
uint256 currentTokenId;
uint256 currentTokenPoints;
uint256 lastTokenPoints;
uint32 counter = 0;
uint256 maxRange = 13;
if(tokens.length < 201){
maxRange = 10;
}
while(payoutRange < maxRange){
uint256 inRangecounter = payDistributionAmount[payoutRange];
while(inRangecounter > 0){
currentTokenId = sortedWinners[counter];
currentTokenPoints = tokenToPointsMap[currentTokenId];
inRangecounter--;
//Special case for the last one
if(inRangecounter == 0 && payoutRange == maxRange - 1){
if(currentTokenPoints == lastTokenPoints){
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
} else {
tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange];
}
}
//Fix second condition
if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){
for(uint256 i = 0; i < tokenEqualsCounter; i++){
tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter);
}
percent = 0;
tokensEquals = new uint[](30);
tokenEqualsCounter = 0;
}
percent += payoutDistribution[payoutRange];
tokensEquals[tokenEqualsCounter] = currentTokenId;
tokenEqualsCounter++;
counter++;
lastTokenPoints = currentTokenPoints;
}
payoutRange++;
}
pValidationState = pointsValidationState.TopWinnersAssigned;
lastPrizeGiven = counter;
}
/**
* @notice Sets prize percentage to every address that wins from the position 30th onwards
* @dev If there are less than 300 tokens playing, then this function will set nothing.
* @param amount tokens in a chunk
*/
function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){
require(lastPrizeGiven + amount <= winnerCounter);
uint16 inRangeCounter = payDistributionAmount[payoutRange];
for(uint256 i = 0; i < amount; i++){
if (inRangeCounter == 0){
payoutRange++;
inRangeCounter = payDistributionAmount[payoutRange];
}
uint256 tokenId = sortedWinners[i + lastPrizeGiven];
tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange];
inRangeCounter--;
}
//i + amount prize was not given yet, so amount -1
lastPrizeGiven += amount;
payDistributionAmount[payoutRange] = inRangeCounter;
if(lastPrizeGiven == winnerCounter){
pValidationState = pointsValidationState.WinnersAssigned;
return;
}
}
/**
* @notice Sets prizes for last tokens and sets prize pool amount
*/
function setEnd() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){
uint256 balance = address(this).balance;
adminPool = balance.mul(10).div(100);
prizePool = balance.mul(90).div(100);
pValidationState = pointsValidationState.Finished;
gameFinishedTime = now;
unSetPause();
}
}
// File: contracts/CryptocupNFL.sol
contract CryptocupNFL is GameRegistry {
constructor() public {
adminAddress = msg.sender;
deploymentTime = now;
_prepareMatchResultsArray();
_prepareBonusResultsArray();
}
/**
* @dev Only accept eth from the admin
*/
function() external payable {
require(msg.sender == adminAddress || msg.sender == marketplaceAddress);
}
function buildToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogTokenBuilt(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function giftToken(address giftedAddress, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[giftedAddress].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(giftedAddress, tokenId);
emit LogTokenGift(msg.sender, giftedAddress, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
function buildPrepaidToken(bytes32 secret) external payable onlyAdmin isNotPaused {
require(msg.value >= _getTokenPrice(), "Eth sent is not enough.");
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(now < EVENT_START, "Event already started."); //Event Start
secretsMap[secret] = 1;
emit LogPrepaidTokenBuilt(msg.sender, secret);
}
function redeemPrepaidToken(bytes32 preSecret, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external isNotPaused returns(uint256){
require(msg.sender != address(0), "Sender cannot be 0 address.");
require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens.");
require(now < EVENT_START, "Event already started."); //Event Start
require (bytes(message).length <= 100);
bytes32 secret = keccak256(preSecret);
require (secretsMap[secret] == 1, "Invalid secret.");
secretsMap[secret] = 0;
uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message);
_mint(msg.sender, tokenId);
emit LogPrepaidRedeemed(msg.sender, tokenId, message, matches, extraStats, bonusMatches);
return tokenId;
}
/**
* @param tokenId - ID of token to get.
* @return Returns all the valuable information about a specific token.
*/
function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) {
Token storage token = tokens[tokenId];
matches = token.matches;
bonusMatches = token.bonusMatches;
extraStats = token.extraStats;
timeStamp = token.timeStamp;
message = token.message;
}
/**
* @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens
* owned by the caller of this function.
* @dev If the caller has no prize, the function will revert costing no gas to the caller.
*/
function withdrawPrize() external checkState(pointsValidationState.Finished){
uint256 prize = 0;
uint256[] memory tokenList = ownedTokens[msg.sender];
for(uint256 i = 0;i < tokenList.length; i++){
prize += tokenToPayoutMap[tokenList[i]];
tokenToPayoutMap[tokenList[i]] = 0;
}
require(prize > 0);
msg.sender.transfer((prizePool.mul(prize)).div(1000000));
}
//EMERGENCY CALLS
//If something goes wrong or fails, these functions will allow retribution for token holders
/**
* @notice if there is an unresolvable problem, users can call to this function to get a refund.
*/
function emergencyWithdraw() external hasFinalized{
uint256 balance = STARTING_PRICE * ownedTokens[msg.sender].length;
delete ownedTokens[msg.sender];
msg.sender.transfer(balance);
}
} | Sets the id of the last token that will be given a prize. This is done to offload some of the calculations needed for sorting, and to cap the number of sorts needed to just the winners and not the whole array of tokens. tokenId last token id/ | function setLimit(uint256 tokenId) external onlyAdmin{
require(tokenId < tokens.length);
require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet);
pointsLimit = tokenId;
pValidationState = pointsValidationState.LimitSet;
lastCheckedToken = 0;
lastCalculatedToken = 0;
winnerCounter = 0;
setPause();
setPayoutDistributionId();
}
| 12,723,309 |
pragma solidity 0.4.24;
/**
* @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;
}
}
/**
* @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 SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title 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 Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title 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
* 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;
}
}
/**
* @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));
}
}
/* solium-disable security/no-block-members */
pragma solidity ^0.4.24;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _token ERC20 token which is being vested
*/
function release(ERC20Basic _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20Basic _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
/** @title Periodic Token Vesting
* @dev A token holder contract that can release its token balance periodically like a
* typical vesting scheme. Optionally revocable by the owner.
*/
contract PeriodicTokenVesting is TokenVesting {
using SafeMath for uint256;
uint256 public releasePeriod;
uint256 public releaseCount;
mapping (address => uint256) public revokedAmount;
constructor(
address _beneficiary,
uint256 _startInUnixEpochTime,
uint256 _releasePeriodInSeconds,
uint256 _releaseCount
)
public
TokenVesting(_beneficiary, _startInUnixEpochTime, 0, _releasePeriodInSeconds.mul(_releaseCount), true)
{
require(_releasePeriodInSeconds.mul(_releaseCount) > 0, "Vesting Duration cannot be 0");
require(_startInUnixEpochTime.add(_releasePeriodInSeconds.mul(_releaseCount)) > block.timestamp, "Worthless vesting");
releasePeriod = _releasePeriodInSeconds;
releaseCount = _releaseCount;
}
function initialTokenAmountInVesting(ERC20Basic _token) public view returns (uint256) {
return _token.balanceOf(address(this)).add(released[_token]).add(revokedAmount[_token]);
}
function tokenAmountLockedInVesting(ERC20Basic _token) public view returns (uint256) {
return _token.balanceOf(address(this)).sub(releasableAmount(_token));
}
function nextVestingTime(ERC20Basic _token) public view returns (uint256) {
if (block.timestamp >= start.add(duration) || revoked[_token]) {
return 0;
} else {
return start.add(((block.timestamp.sub(start)).div(releasePeriod).add(1)).mul(releasePeriod));
}
}
function vestingCompletionTime(ERC20Basic _token) public view returns (uint256) {
if (block.timestamp >= start.add(duration) || revoked[_token]) {
return 0;
} else {
return start.add(duration);
}
}
function remainingVestingCount(ERC20Basic _token) public view returns (uint256) {
if (block.timestamp >= start.add(duration) || revoked[_token]) {
return 0;
} else {
return releaseCount.sub((block.timestamp.sub(start)).div(releasePeriod));
}
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20Basic _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
revokedAmount[_token] = refund;
_token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul((block.timestamp.sub(start)).div(releasePeriod)).div(releaseCount);
}
}
}
/** @title Cnus Token
* An ERC20-compliant token.
*/
contract CnusToken is StandardToken, Ownable, BurnableToken {
using SafeMath for uint256;
// global token transfer lock
bool public globalTokenTransferLock = false;
bool public mintingFinished = false;
bool public lockingDisabled = false;
string public name = "CoinUs";
string public symbol = "CNUS";
uint256 public decimals = 18;
address public mintContractOwner;
address[] public vestedAddresses;
// mapping that provides address based lock.
mapping( address => bool ) public lockedStatusAddress;
mapping( address => PeriodicTokenVesting ) private tokenVestingContracts;
event LockingDisabled();
event GlobalLocked();
event GlobalUnlocked();
event Locked(address indexed lockedAddress);
event Unlocked(address indexed unlockedaddress);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event VestingCreated(address indexed beneficiary, uint256 startTime, uint256 period, uint256 releaseCount);
event InitialVestingDeposited(address indexed beneficiary, uint256 amount);
event AllVestedTokenReleased();
event VestedTokenReleased(address indexed beneficiary);
event RevokedTokenVesting(address indexed beneficiary);
// Check for global lock status to be unlocked
modifier checkGlobalTokenTransferLock {
if (!lockingDisabled) {
require(!globalTokenTransferLock, "Global lock is active");
}
_;
}
// Check for address lock to be unlocked
modifier checkAddressLock {
require(!lockedStatusAddress[msg.sender], "Address is locked");
_;
}
modifier canMint() {
require(!mintingFinished, "Minting is finished");
_;
}
modifier hasMintPermission() {
require(msg.sender == mintContractOwner, "Minting is not authorized from this account");
_;
}
constructor() public {
uint256 initialSupply = 2000000000;
initialSupply = initialSupply.mul(10**18);
totalSupply_ = initialSupply;
balances[msg.sender] = initialSupply;
mintContractOwner = msg.sender;
}
function disableLockingForever() public
onlyOwner
{
lockingDisabled = true;
emit LockingDisabled();
}
function setGlobalTokenTransferLock(bool locked) public
onlyOwner
{
require(!lockingDisabled);
require(globalTokenTransferLock != locked);
globalTokenTransferLock = locked;
if (globalTokenTransferLock) {
emit GlobalLocked();
} else {
emit GlobalUnlocked();
}
}
/**
* @dev Allows token issuer to lock token transfer for an address.
* @param target Target address to lock token transfer.
*/
function lockAddress(
address target
)
public
onlyOwner
{
require(!lockingDisabled);
require(owner != target);
require(!lockedStatusAddress[target]);
for(uint256 i = 0; i < vestedAddresses.length; i++) {
require(tokenVestingContracts[vestedAddresses[i]] != target);
}
lockedStatusAddress[target] = true;
emit Locked(target);
}
/**
* @dev Allows token issuer to unlock token transfer for an address.
* @param target Target address to unlock token transfer.
*/
function unlockAddress(
address target
)
public
onlyOwner
{
require(!lockingDisabled);
require(lockedStatusAddress[target]);
lockedStatusAddress[target] = false;
emit Unlocked(target);
}
/**
* @dev Creates a vesting contract that vests its balance of Cnus token to the
* _beneficiary, gradually in periodic interval until all of the balance will have
* vested by period * release count time.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _startInUnixEpochTime the time (as Unix time) at which point vesting starts
* @param _releasePeriodInSeconds period in seconds in which tokens will vest to beneficiary
* @param _releaseCount count of period required to have all of the balance vested
*/
function createNewVesting(
address _beneficiary,
uint256 _startInUnixEpochTime,
uint256 _releasePeriodInSeconds,
uint256 _releaseCount
)
public
onlyOwner
{
require(tokenVestingContracts[_beneficiary] == address(0));
tokenVestingContracts[_beneficiary] = new PeriodicTokenVesting(
_beneficiary, _startInUnixEpochTime, _releasePeriodInSeconds, _releaseCount);
vestedAddresses.push(_beneficiary);
emit VestingCreated(_beneficiary, _startInUnixEpochTime, _releasePeriodInSeconds, _releaseCount);
}
/**
* @dev Transfers token vesting amount from token issuer to vesting contract created for the
* beneficiary. Token Issuer must first approve token spending from owner's account.
* @param _beneficiary beneficiary for whom vesting has been created with createNewVesting function.
* @param _vestAmount vesting amount for the beneficiary
*/
function transferInitialVestAmountFromOwner(
address _beneficiary,
uint256 _vestAmount
)
public
onlyOwner
returns (bool)
{
require(tokenVestingContracts[_beneficiary] != address(0));
ERC20 cnusToken = ERC20(address(this));
require(cnusToken.allowance(owner, address(this)) >= _vestAmount);
require(cnusToken.transferFrom(owner, tokenVestingContracts[_beneficiary], _vestAmount));
emit InitialVestingDeposited(_beneficiary, cnusToken.balanceOf(tokenVestingContracts[_beneficiary]));
return true;
}
function checkVestedAddressCount()
public
view
returns (uint256)
{
return vestedAddresses.length;
}
function checkCurrentTotolVestedAmount()
public
view
returns (uint256)
{
uint256 vestedAmountSum = 0;
for (uint256 i = 0; i < vestedAddresses.length; i++) {
vestedAmountSum = vestedAmountSum.add(
tokenVestingContracts[vestedAddresses[i]].vestedAmount(ERC20(address(this))));
}
return vestedAmountSum;
}
function checkCurrentTotalReleasableAmount()
public
view
returns (uint256)
{
uint256 releasableAmountSum = 0;
for (uint256 i = 0; i < vestedAddresses.length; i++) {
releasableAmountSum = releasableAmountSum.add(
tokenVestingContracts[vestedAddresses[i]].releasableAmount(ERC20(address(this))));
}
return releasableAmountSum;
}
function checkCurrentTotalAmountLockedInVesting()
public
view
returns (uint256)
{
uint256 lockedAmountSum = 0;
for (uint256 i = 0; i < vestedAddresses.length; i++) {
lockedAmountSum = lockedAmountSum.add(
tokenVestingContracts[vestedAddresses[i]].tokenAmountLockedInVesting(ERC20(address(this))));
}
return lockedAmountSum;
}
function checkInitialTotalTokenAmountInVesting()
public
view
returns (uint256)
{
uint256 initialTokenVesting = 0;
for (uint256 i = 0; i < vestedAddresses.length; i++) {
initialTokenVesting = initialTokenVesting.add(
tokenVestingContracts[vestedAddresses[i]].initialTokenAmountInVesting(ERC20(address(this))));
}
return initialTokenVesting;
}
function checkNextVestingTimeForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].nextVestingTime(ERC20(address(this)));
}
function checkVestingCompletionTimeForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].vestingCompletionTime(ERC20(address(this)));
}
function checkRemainingVestingCountForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].remainingVestingCount(ERC20(address(this)));
}
function checkReleasableAmountForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].releasableAmount(ERC20(address(this)));
}
function checkVestedAmountForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].vestedAmount(ERC20(address(this)));
}
function checkTokenAmountLockedInVestingForBeneficiary(
address _beneficiary
)
public
view
returns (uint256)
{
require(tokenVestingContracts[_beneficiary] != address(0));
return tokenVestingContracts[_beneficiary].tokenAmountLockedInVesting(ERC20(address(this)));
}
/**
* @notice Transfers vested tokens to all beneficiaries.
*/
function releaseAllVestedToken()
public
checkGlobalTokenTransferLock
returns (bool)
{
emit AllVestedTokenReleased();
PeriodicTokenVesting tokenVesting;
for(uint256 i = 0; i < vestedAddresses.length; i++) {
tokenVesting = tokenVestingContracts[vestedAddresses[i]];
if(tokenVesting.releasableAmount(ERC20(address(this))) > 0) {
tokenVesting.release(ERC20(address(this)));
emit VestedTokenReleased(vestedAddresses[i]);
}
}
return true;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _beneficiary Beneficiary to whom cnus token is being vested
*/
function releaseVestedToken(
address _beneficiary
)
public
checkGlobalTokenTransferLock
returns (bool)
{
require(tokenVestingContracts[_beneficiary] != address(0));
tokenVestingContracts[_beneficiary].release(ERC20(address(this)));
emit VestedTokenReleased(_beneficiary);
return true;
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _beneficiary Beneficiary to whom cnus token is being vested
*/
function revokeTokenVesting(
address _beneficiary
)
public
onlyOwner
checkGlobalTokenTransferLock
returns (bool)
{
require(tokenVestingContracts[_beneficiary] != address(0));
tokenVestingContracts[_beneficiary].revoke(ERC20(address(this)));
_transferMisplacedToken(owner, address(this), ERC20(address(this)).balanceOf(address(this)));
emit RevokedTokenVesting(_beneficiary);
return true;
}
/** @dev Transfer `_value` token to `_to` from `msg.sender`, on the condition
* that global token lock and individual address lock in the `msg.sender`
* accountare both released.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
* @return Whether the transfer was successful or not.
*/
function transfer(
address _to,
uint256 _value
)
public
checkGlobalTokenTransferLock
checkAddressLock
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
checkGlobalTokenTransferLock
returns (bool)
{
require(!lockedStatusAddress[_from], "Address is locked.");
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender address The address which will spend the funds.
* @param _value uint256 The amount of tokens to be spent.
*/
function approve(
address _spender,
uint256 _value
)
public
checkGlobalTokenTransferLock
checkAddressLock
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @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
checkGlobalTokenTransferLock
checkAddressLock
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @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
checkGlobalTokenTransferLock
checkAddressLock
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* @dev Function to transfer mint ownership.
* @param _newOwner The address that will have the mint ownership.
*/
function transferMintOwnership(
address _newOwner
)
public
onlyOwner
{
_transferMintOwnership(_newOwner);
}
/**
* @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
hasMintPermission
canMint
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()
public
onlyOwner
canMint
returns (bool)
{
mintingFinished = true;
emit MintFinished();
return true;
}
function checkMisplacedTokenBalance(
address _tokenAddress
)
public
view
returns (uint256)
{
ERC20 unknownToken = ERC20(_tokenAddress);
return unknownToken.balanceOf(address(this));
}
// Allow transfer of accidentally sent ERC20 tokens
function refundMisplacedToken(
address _recipient,
address _tokenAddress,
uint256 _value
)
public
onlyOwner
{
_transferMisplacedToken(_recipient, _tokenAddress, _value);
}
function _transferMintOwnership(
address _newOwner
)
internal
{
require(_newOwner != address(0));
emit MintOwnershipTransferred(mintContractOwner, _newOwner);
mintContractOwner = _newOwner;
}
function _transferMisplacedToken(
address _recipient,
address _tokenAddress,
uint256 _value
)
internal
{
require(_recipient != address(0));
ERC20 unknownToken = ERC20(_tokenAddress);
require(unknownToken.balanceOf(address(this)) >= _value, "Insufficient token balance.");
require(unknownToken.transfer(_recipient, _value));
}
} | Allow transfer of accidentally sent ERC20 tokens | function refundMisplacedToken(
address _recipient,
address _tokenAddress,
uint256 _value
)
public
onlyOwner
{
_transferMisplacedToken(_recipient, _tokenAddress, _value);
}
| 973,224 |
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
pragma solidity ^0.6.0;
import "../interfaces/GasTokenInterface.sol";
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
pragma solidity ^0.6.0;
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
pragma solidity ^0.6.0;
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsStable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
pragma solidity ^0.6.0;
/**
@title ILendingPoolAddressesProvider interface
@notice provides the interface to fetch the LendingPoolCore address
*/
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
pragma solidity ^0.6.0;
import "../interfaces/ERC20.sol";
import "./Address.sol";
import "./SafeMath.sol";
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
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");
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
pragma solidity ^0.6.0;
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.6.0;
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
}
}
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
import "../interfaces/DSProxyInterface.sol";
import "./SafeERC20.sol";
/// @title Pulls a specified amount of tokens from the EOA owner account to the proxy
contract PullTokensProxy {
using SafeERC20 for ERC20;
/// @notice Pulls a token from the proxyOwner -> proxy
/// @dev Proxy owner must first give approve to the proxy address
/// @param _tokenAddr Address of the ERC20 token
/// @param _amount Amount of tokens which will be transfered to the proxy
function pullTokens(address _tokenAddr, uint _amount) public {
address proxyOwner = DSProxyInterface(address(this)).owner();
ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount);
}
}
pragma solidity ^0.6.0;
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../auth/Auth.sol";
import "../interfaces/DSProxyInterface.sol";
// 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/>.
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
pragma solidity ^0.6.0;
import "./AdminAuth.sol";
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/ILendingPool.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/ILoanShifter.sol";
import "../interfaces/DSProxyInterface.sol";
import "../interfaces/Vat.sol";
import "../interfaces/Manager.sol";
import "../interfaces/IMCDSubscriptions.sol";
import "../interfaces/ICompoundSubscriptions.sol";
import "../auth/AdminAuth.sol";
import "../auth/ProxyPermission.sol";
import "../exchangeV3/DFSExchangeData.sol";
import "./ShifterRegistry.sol";
import "../utils/GasBurner.sol";
import "../loggers/DefisaverLogger.sol";
/// @title LoanShifterTaker Entry point for using the shifting operation
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
// encode data
bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return getUnderlyingAddr(_address);
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function logEvent(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
pragma solidity ^0.6.0;
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
pragma solidity ^0.6.0;
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
pragma solidity ^0.6.0;
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
pragma solidity ^0.6.0;
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
pragma solidity ^0.6.0;
import "../DS/DSGuard.sol";
import "../DS/DSAuth.sol";
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address wrapper;
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
pragma solidity ^0.6.0;
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
pragma solidity ^0.6.0;
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
pragma solidity ^0.6.0;
import "./DSAuthority.sol";
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
pragma solidity ^0.6.0;
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
contract MCDCreateTaker is GasBurner {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable burnGas(20) {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../loggers/DefisaverLogger.sol";
import "../../utils/Discount.sol";
import "../../interfaces/Spotter.sol";
import "../../interfaces/Jug.sol";
import "../../interfaces/DaiJoin.sol";
import "../../interfaces/Join.sol";
import "./MCDSaverProxyHelper.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
/// @title Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId));
uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
Manager(_managerAddr).ilks(_cdpId),
Manager(_managerAddr).urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @param _managerAddr Address of the CDP Manager
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @param _managerAddr Address of the CDP Manager
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
if (feeAmount > _amount / 5) {
feeAmount = _amount / 5;
}
address walletAddr = _feeRecipient.getFeeAddr();
ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount);
return feeAmount;
}
return 0;
}
}
pragma solidity ^0.6.0;
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
pragma solidity ^0.6.0;
import "./PipInterface.sol";
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
pragma solidity ^0.6.0;
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
pragma solidity ^0.6.0;
import "./Vat.sol";
import "./Gem.sol";
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
pragma solidity ^0.6.0;
import "./Gem.sol";
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
pragma solidity ^0.6.0;
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../interfaces/Vat.sol";
/// @title Helper methods for MCDSaverProxy
contract MCDSaverProxyHelper is DSMath {
enum ManagerType { MCD, BPROTOCOL }
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
/// @notice Based on the manager type returns the address
/// @param _managerType Type of vault manager to use
function getManagerAddr(ManagerType _managerType) public pure returns (address) {
if (_managerType == ManagerType.MCD) {
return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
} else if (_managerType == ManagerType.BPROTOCOL) {
return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed;
}
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/ZrxAllowlist.sol";
import "./DFSExchangeData.sol";
import "./DFSExchangeHelper.sol";
import "../exchange/SaverExchangeRegistry.sol";
import "../interfaces/OffchainWrapperInterface.sol";
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
return (false, 0);
}
if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) {
return (false, 0);
}
// send src amount
ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount);
return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
pragma solidity ^0.6.0;
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
pragma solidity ^0.6.0;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
pragma solidity ^0.6.0;
import "./DSAuth.sol";
import "./DSNote.sol";
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
pragma solidity ^0.6.0;
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
pragma solidity ^0.6.0;
abstract contract TokenInterface {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
contract DFSExchangeHelper {
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
address walletAddr = _feeRecipient.getFeeAddr();
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src;
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchangeV3/DFSExchangeData.sol";
abstract contract OffchainWrapperInterface is DFSExchangeData {
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) virtual public payable returns (bool success, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract IFeeRecipient {
function getFeeAddr() public view virtual returns (address);
function changeWalletAddr(address _newWallet) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../saver/MCDSaverProxy.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/ITokenInterface.sol";
import "../../DS/DSAuth.sol";
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ProtocolInterface.sol";
import "../interfaces/ERC20.sol";
import "../interfaces/ITokenInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "./dydx/ISoloMargin.sol";
import "./SavingsLogger.sol";
import "./dsr/DSRSavingsProtocol.sol";
import "./compound/CompoundSavingsProtocol.sol";
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
function borrowCaps(address) external virtual returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (public virtually)
Sell, // sell an amount of some token (public virtually)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function ownerSetSpreadPremium(
uint256 marketId,
Decimal.D256 memory spreadPremium
) public virtual;
function getIsGlobalOperator(address operator) public virtual view returns (bool);
function getMarketTokenAddress(uint256 marketId)
public virtual
view
returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter)
public virtual;
function getAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId)
public virtual
view
returns (address);
function getMarketInterestSetter(uint256 marketId)
public virtual
view
returns (address);
function getMarketSpreadPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getNumMarkets() public virtual view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient)
public virtual
returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue)
public virtual;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual;
function getIsLocalOperator(address owner, address operator)
public virtual
view
returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Par memory);
function ownerSetMarginPremium(
uint256 marketId,
Decimal.D256 memory marginPremium
) public virtual;
function getMarginRatio() public virtual view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) public virtual view returns (bool);
function getRiskParams() public virtual view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
public virtual
view
returns (address[] memory, Types.Par[] memory, Types.Wei[] memory);
function renounceOwnership() public virtual;
function getMinBorrowedValue() public virtual view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) public virtual;
function getMarketPrice(uint256 marketId) public virtual view returns (address);
function owner() public virtual view returns (address);
function isOwner() public virtual view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient)
public virtual
returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) public virtual;
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getMarketWithInfo(uint256 marketId)
public virtual
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual;
function getLiquidationSpread() public virtual view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId)
public virtual
view
returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) public virtual view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account)
public virtual
view
returns (uint8);
function getEarningsRate() public virtual view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual;
function getRiskLimits() public virtual view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId)
public virtual
view
returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual;
function ownerSetGlobalOperator(address operator, bool approved) public virtual;
function transferOwnership(address newOwner) public virtual;
function getAdjustedAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId)
public virtual
view
returns (Interest.Rate memory);
}
pragma solidity ^0.6.0;
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../DS/DSMath.sol";
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../compound/helpers/Exponential.sol";
import "../../interfaces/ERC20.sol";
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
import "./CarefulMath.sol";
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
pragma solidity ^0.6.0;
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "./ISoloMargin.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
address market,
uint256 rateMode,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelperV2 is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
uint public constant STABLE_ID = 1;
uint public constant VARIABLE_ID = 2;
/// @notice Calculates the gas cost for transaction
/// @param _oracleAddress address of oracle used
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
gasCost = _gasCost;
// gas cost can't go over 10% of the whole amount
if (gasCost > (_amount / 10)) {
gasCost = _amount / 10;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) internal {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) internal {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) {
return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProviderV2 {
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPoolV2 {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
**/
function withdraw(
address asset,
uint256 amount,
address to
) external;
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external;
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2);
function setPause(bool val) external;
function paused() external view returns (bool);
}
pragma solidity ^0.6.0;
/************
@title IPriceOracleGetterAave interface
@notice Interface for the Aave price oracle.*/
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
abstract contract IAaveProtocolDataProviderV2 {
struct TokenData {
string symbol;
address tokenAddress;
}
function getAllReservesTokens() external virtual view returns (TokenData[] memory);
function getAllATokens() external virtual view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external virtual
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external virtual
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external virtual
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external virtual
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
ManagerType managerType;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable burnGas(20) {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
address managerAddr = getManagerAddr(_closeData.managerType);
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId));
}
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILoanShifter.sol";
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../mcd/create/MCDCreateProxyActions.sol";
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(address(manager), _cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(address(manager), _cdpId, _joinAddr, collAmount);
// draw debt
drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
pragma solidity ^0.6.0;
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "./MCDCreateProxyActions.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../DS/DSProxy.sol";
import "./MCDCreateTaker.sol";
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "./SafeERC20.sol";
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./saver/MCDSaverProxyHelper.sol";
import "../interfaces/Spotter.sol";
contract MCDLoanInfo is MCDSaverProxyHelper {
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
struct VaultInfo {
address owner;
uint256 ratio;
uint256 collateral;
uint256 debt;
bytes32 ilk;
address urn;
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) {
address urn = manager.urns(_cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint256 collateral, uint256 debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
vaultInfo = VaultInfo({
owner: manager.owns(_cdpId),
ratio: getRatio(_cdpId, ilk),
collateral: collateral,
debt: debt,
ilk: ilk,
urn: urn
});
}
function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) {
vaultInfos = new VaultInfo[](_cdps.length);
for (uint256 i = 0; i < _cdps.length; i++) {
vaultInfos[i] = getVaultInfo(_cdps[i]);
}
}
function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) {
ratios = new uint256[](_cdps.length);
for (uint256 i = 0; i<_cdps.length; i++) {
bytes32 ilk = manager.ilks(_cdps[i]);
ratios[i] = getRatio(_cdps[i], ilk);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "./StaticV2.sol";
import "../saver/MCDSaverProxy.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../auth/AdminAuth.sol";
/// @title Handles subscriptions for automatic monitoring
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
pragma solidity ^0.6.0;
/// @title Implements enum Method
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Flipper.sol";
import "../../interfaces/Gem.sol";
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
if(Join(_joinAddr).dec() != 18) {
amount = amount / (10**(18 - Join(_joinAddr).dec()));
}
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
pragma solidity ^0.6.0;
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./ISubscriptionsV2.sol";
import "./StaticV2.sol";
import "./MCDMonitorProxyV2.sol";
/// @title Implements logic that allows bots to call Boost and Repay
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1000000;
uint public BOOST_GAS_COST = 1000000;
bytes4 public REPAY_SELECTOR = 0xf360ce20;
bytes4 public BOOST_SELECTOR = 0x8ec2ae25;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./StaticV2.sol";
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Implements logic for calling MCDSaverProxy always from same contract
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
uint public MIN_CHANGE_PERIOD = 6 * 1 hours;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../compound/helpers/Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for cream contracts
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
pragma solidity ^0.6.0;
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
pragma solidity ^0.6.0;
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CreamSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "../utils/ZrxAllowlist.sol";
import "./SaverExchangeHelper.sol";
import "./SaverExchangeRegistry.sol";
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CompoundSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "./Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for Compound contracts
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
import "../../compound/helpers/CompoundSaverHelper.sol";
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
_exData.srcAmount = borrowAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "../utils/FlashLoanReceiverBase.sol";
import "../interfaces/DSProxyInterface.sol";
import "../exchangeV3/DFSExchangeCore.sol";
import "./ShifterRegistry.sol";
import "./LoanShifterTaker.sol";
/// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy
contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth {
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
ShifterRegistry public constant shifterRegistry =
ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData) =
packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendTokenToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(paramData.proxy).owner();
if (paramData.swapType == 1) {
// COLL_SWAP
(, uint256 amount) = _sell(exchangeData);
sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) {
// DEBT_SWAP
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendTokenToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
ERC20(exchangeData.srcAddr).balanceOf(address(this))
);
} else {
// NO_SWAP just send tokens to proxy
sendTokenAndEthToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
getBalance(exchangeData.srcAddr)
);
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(
uint256 _amount,
uint256 _fee,
bytes memory _params
)
internal
pure
returns (ParamData memory paramData, ExchangeData memory exchangeData)
{
LoanShifterTaker.LoanShiftData memory shiftData;
address proxy;
(shiftData, exchangeData, proxy) = abi.decode(
_params,
(LoanShifterTaker.LoanShiftData, ExchangeData, address)
);
bytes memory proxyData1;
bytes memory proxyData2;
uint256 openDebtAmount = (_amount + _fee);
if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER FROM
proxyData1 = abi.encodeWithSignature(
"close(uint256,address,uint256,uint256)",
shiftData.id1,
shiftData.addrLoan1,
_amount,
shiftData.collAmount
);
} else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND FROM
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData1 = abi.encodeWithSignature(
"changeDebt(address,address,uint256,uint256)",
shiftData.debtAddr1,
shiftData.debtAddr2,
_amount,
exchangeData.srcAmount
);
} else {
proxyData1 = abi.encodeWithSignature(
"close(address,address,uint256,uint256)",
shiftData.addrLoan1,
shiftData.debtAddr1,
shiftData.collAmount,
shiftData.debtAmount
);
}
}
if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER TO
proxyData2 = abi.encodeWithSignature(
"open(uint256,address,uint256)",
shiftData.id2,
shiftData.addrLoan2,
openDebtAmount
);
} else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND TO
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2);
} else {
proxyData2 = abi.encodeWithSignature(
"open(address,address,uint256)",
shiftData.addrLoan2,
shiftData.debtAddr2,
openDebtAmount
);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: shiftData.debtAddr1,
protocol1: uint8(shiftData.fromProtocol),
protocol2: uint8(shiftData.toProtocol),
swapType: uint8(shiftData.swapType)
});
}
function sendTokenAndEthToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function sendTokenToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
} else {
_proxy.transfer(address(this).balance);
}
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../DS/DSProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../shifter/ShifterRegistry.sol";
import "./CompoundCreateTaker.sol";
/// @title Contract that receives the FL from Aave for Creating loans
contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner();
_sell(exchangeData);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
CompoundCreateTaker.CreateInfo memory createData;
address proxy;
(createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee));
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: createData.cCollAddress,
cDebtAddr: createData.cBorrowAddress
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
/// @title Opens compound positions with a leverage
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
DFSExchangeData.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/ProxyPermission.sol";
import "../utils/DydxFlashLoanBase.sol";
import "../loggers/DefisaverLogger.sol";
import "../interfaces/ERC20.sol";
/// @title Takes flash loan
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../utils/SafeMath.sol";
import "../savings/dydx/ISoloMargin.sol";
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../AaveHelperV2.sol";
import "../../../utils/GasBurner.sol";
import "../../../auth/AdminAuth.sol";
import "../../../auth/ProxyPermission.sol";
import "../../../utils/DydxFlashLoanBase.sol";
import "../../../loggers/DefisaverLogger.sol";
import "../../../interfaces/ProxyRegistryInterface.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../interfaces/ERC20.sol";
import "../../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 {
address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2;
// leaving _flAmount to be the same as the older version
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
// for repay we are using regular flash loan with paying back the flash loan + premium
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
// leaving _flAmount to be the same as the older version
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
uint256[] memory modes = new uint256[](1);
modes[0] = _rateMode;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
import "./DSProxyInterface.sol";
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapExchangeInterface.sol";
import "../../interfaces/UniswapFactoryInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
pragma solidity ^0.6.0;
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
pragma solidity ^0.6.0;
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/SafeERC20.sol";
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "../interfaces/IFeeRecipient.sol";
import "./SaverExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
address walletAddr = _feeRecipient.getFeeAddr();
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchange/SaverExchangeCore.sol";
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
ManagerType managerType;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay,
uint8 managerType
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr,
managerType: ManagerType(managerType)
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId));
uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../mcd/saver/MCDSaverProxyHelper.sol";
import "./MCDCloseTaker.sol";
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
address managerAddr = getManagerAddr(closeDataSent.managerType);
closeCDP(closeData, exchangeData, user, managerAddr);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user,
address _managerAddr
) internal {
paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee);
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == EXCHANGE_WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Imports cream position from the account to DSProxy
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Imports Compound position from the account to DSProxy
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve DSProxy to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this));
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
}
pragma solidity ^0.6.0;
import "../../auth/AdminAuth.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
(address cCollAddr, address cBorrowAddr, address proxy) =
abi.decode(_params, (address, address, address));
address user = DSProxyInterface(proxy).owner();
uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user);
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowAddr, _amount);
// repay compound debt on behalf of the user
require(
CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0,
"Repay borrow behalf fail"
);
bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance);
DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData);
// borrow debt now on ds proxy
bytes memory borrowProxyCallData =
formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData);
// repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call to pull tokens to DSProxy
/// @param _cTokenAddr CToken address of the collateral
/// @param _amount Amount of cTokens to pull
function formatDSProxyPullTokensCall(
address _cTokenAddr,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"pullTokens(address,uint256)",
_cTokenAddr,
_amount
);
}
/// @notice Formats function data call borrow through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
function formatDSProxyBorrowCall(
address _cCollToken,
address _cBorrowToken,
address _borrowToken,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken,
_cBorrowToken,
_borrowToken,
_amount
);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount);
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = _flAmount;
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _market Market in which we want to import
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "../compound/helpers/Exponential.sol";
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../helpers/Exponential.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(
0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B
);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) {
uint256 compBalance = 0;
for (uint256 i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance = add_(comp.compAccrued(_user), compBalance);
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getClaimableAssets(address[] memory _cTokens, address _user)
public
view
returns (bool[] memory supplyClaims, bool[] memory borrowClaims)
{
supplyClaims = new bool[](_cTokens.length);
borrowClaims = new bool[](_cTokens.length);
for (uint256 i = 0; i < _cTokens.length; ++i) {
supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0;
borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0;
}
}
function getSuppyBalance(address _cToken, address _supplier)
public
view
returns (uint256 supplierAccrued)
{
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: comp.compSupplierIndex(_cToken, _supplier)
});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = supplierDelta;
}
function getBorrowBalance(address _cToken, address _borrower)
public
view
returns (uint256 borrowerAccrued)
{
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: comp.compBorrowerIndex(_cToken, _borrower)
});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(
CTokenInterface(_cToken).borrowBalanceStored(_borrower),
marketBorrowIndex
);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = borrowerDelta;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompBalance.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../CompoundBasicProxy.sol";
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.user = msg.sender;
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic compound interactions through the DSProxy
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic cream interactions through the DSProxy
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "./helpers/Exponential.sol";
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompoundSafetyRatio.sol";
import "./helpers/CompoundSaverHelper.sol";
/// @title Gets data about Compound positions
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
uint borrowCap;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]),
borrowCap: comp.borrowCaps(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/BotRegistry.sol";
import "../../utils/GasBurner.sol";
import "./CompoundMonitorProxy.sol";
import "./CompoundSubscriptions.sol";
import "../../interfaces/GasTokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../CompoundSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1500000;
uint public BOOST_GAS_COST = 1000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin {
compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Compound automatization
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "./DFSExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./DFSExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587);
function callSell(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
dfsExchange = DFSExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CreamSafetyRatio.sol";
import "./helpers/CreamSaverHelper.sol";
/// @title Gets data about cream positions
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/ERC20.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchange/SaverExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CreamSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelper.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount = _data.srcAmount;
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelperV2.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/TokenInterface.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this));
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// swap
(, destAmount) = _sell(_data);
}
// take gas cost at the end
destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr);
// payback
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
// if destAmount higher than borrow repay whole debt
uint borrow;
if (_rateMode == STABLE_ID) {
(,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
} else {
(,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
}
ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this)));
// first return 0x fee to tx.origin as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
// borrow amount
ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this));
// take gas cost at the beginning
_data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
(, destAmount) = _sell(_data);
} else {
destAmount = _data.srcAmount;
}
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../utils/SafeERC20.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../DS/DSProxy.sol";
import "../../AaveHelperV2.sol";
import "../../../auth/AdminAuth.sol";
import "../../../exchangeV3/DFSExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal {
(, uint swappedAmount) = _sell(_exchangeData);
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens
uint256 msgValue = 0;
address token = _exchangeData.destAddr;
// sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
msgValue = swappedAmount;
token = ETH_ADDR;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// deposit collateral on behalf of user
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"deposit(address,address,uint256)",
_market,
token,
swappedAmount
)
);
}
function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal {
// we will withdraw exactly the srcAmount, as fee we keep before selling
uint valueToWithdraw = _exchangeData.srcAmount;
// take out the fee wee need to pay and sell the rest
_exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee;
(, uint swappedAmount) = _sell(_exchangeData);
// set protocol fee left to eth balance of this address
// but if destAddr is eth or weth, this also includes that value so we need to substract it
uint protocolFeeLeft = address(this).balance;
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens
uint256 msgValue = 0;
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
protocolFeeLeft -= swappedAmount;
msgValue = swappedAmount;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// first payback the loan with swapped amount
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"payback(address,address,uint256,uint256)",
_market,
_exchangeData.destAddr,
swappedAmount,
_rateMode
)
);
// if some tokens left after payback (full repay) we need to return it back to the proxy owner
require(user != address(0)); // be sure that we fetched the user correctly
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
// keep protocol fee for tx.origin, but the rest of the balance return to the user
payable(user).transfer(address(this).balance - protocolFeeLeft);
} else {
// in case its a token, just return whole value back to the user, as protocol fee is always in eth
uint amount = ERC20(_exchangeData.destAddr).balanceOf(user);
ERC20(_exchangeData.destAddr).safeTransfer(user, amount);
}
// pull the amount we flash loaned in collateral to be able to payback the debt
DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw));
}
function executeOperation(
address[] calldata,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) public returns (bool) {
(
bytes memory exchangeDataBytes,
address market,
uint256 gasCost,
uint256 rateMode,
bool isRepay,
address proxy
)
= abi.decode(params, (bytes,address,uint256,uint256,bool,address));
require(initiator == proxy, "initiator isn't proxy");
ExchangeData memory exData = unpackExchangeData(exchangeDataBytes);
exData.user = DSAuth(proxy).owner();
exData.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// this is to avoid stack too deep
uint fee = premiums[0];
uint totalValueToReturn = exData.srcAmount + fee;
// if its repay, we are using regular flash loan and payback the premiums
if (isRepay) {
repay(exData, market, gasCost, proxy, rateMode, fee);
address token = exData.srcAddr;
if (token == ETH_ADDR || token == WETH_ADDRESS) {
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)();
token = WETH_ADDRESS;
}
ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn);
} else {
boost(exData, market, gasCost, proxy);
}
tx.origin.transfer(address(this).balance);
return true;
}
/// @dev allow contract to receive eth from sell
receive() external override payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImportV2 is AaveHelperV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address market,
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market);
uint256 globalBorrowAmountStable = 0;
uint256 globalBorrowAmountVariable = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user);
if (borrowsStable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID));
globalBorrowAmountStable = borrowsStable;
}
if (borrowsVariable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID));
globalBorrowAmountVariable = borrowsVariable;
}
}
if (globalBorrowAmountVariable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID);
}
if (globalBorrowAmountStable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID);
}
(address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken);
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal {
// payback on behalf of user
if (_token != ETH_ADDR) {
ERC20(_token).safeApprove(_proxy, _amount);
DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
} else {
DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
}
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelperV2.sol";
import "../interfaces/ILendingPoolV2.sol";
contract AaveSafetyRatioV2 is AaveHelperV2 {
function getSafetyRatio(address _market, address _user) public view returns(uint256) {
ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool());
(,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user);
if (totalDebtETH == 0) return uint256(0);
return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./AaveMonitorProxyV2.sol";
import "./AaveSubscriptionsV2.sol";
import "../AaveSafetyRatioV2.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorV2";
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5;
AaveMonitorProxyV2 public aaveMonitorProxy;
AaveSubscriptionsV2 public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptionsV2(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptionsV2.AaveHolder memory holder;
holder = subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxyV2 is AdminAuth {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorProxyV2";
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Owner is able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Owner is able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point owner is able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptionsV2 is AdminAuth {
string public constant NAME = "AaveSubscriptionsV2";
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "./AaveHelperV2.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 {
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
if (_tokenAddr == ETH_ADDR) {
require(msg.value == _amount);
TokenInterface(WETH_ADDRESS).deposit{value: _amount}();
_tokenAddr = WETH_ADDRESS;
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount
function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
// if weth, pull to proxy and return ETH to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this));
// needs to use balance of in case that amount is -1 for whole debt
TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this)));
msg.sender.transfer(address(this).balance);
} else {
// if not eth send directly to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender);
}
}
/// @notice User borrows tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable
function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this));
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this)));
if (_tokenAddr == WETH_ADDRESS) {
// Pull if we have any eth leftover
TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this)));
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this)));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf);
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
// stable = 1, variable = 2
function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode);
}
function changeToWeth(address _token) private view returns(address) {
if (_token == ETH_ADDR) {
return WETH_ADDRESS;
}
return _token;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatioV2.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
contract AaveLoanInfoV2 is AaveSafetyRatioV2 {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowStableAmounts;
uint256[] borrowVariableAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRateVariable;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
bool borrowinEnabled;
bool stableBorrowRateEnabled;
}
struct ReserveData {
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 liquidityRate;
uint256 variableBorrowRate;
uint256 stableBorrowRate;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrowsStable;
uint256 borrowsVariable;
uint256 stableBorrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
function getRatio(address _market, address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_market, _user);
}
/// @notice Fetches Aave prices for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens);
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]);
}
}
function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_market, _users[i]);
}
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]);
(address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: aToken,
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) {
(
, // uint256 decimals
uint256 ltv,
uint256 liquidationThreshold,
, // uint256 liquidationBonus
, // uint256 reserveFactor
bool usageAsCollateralEnabled,
bool borrowinEnabled,
bool stableBorrowRateEnabled,
, // bool isActive
// bool isFrozen
) = _dataProvider.getReserveConfigurationData(_token);
ReserveData memory t;
(
t.availableLiquidity,
t.totalStableDebt,
t.totalVariableDebt,
t.liquidityRate,
t.variableBorrowRate,
t.stableBorrowRate,
,
,
,
) = _dataProvider.getReserveData(_token);
(address aToken,,) = _dataProvider.getReserveTokensAddresses(_token);
uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token);
_tokenInfo = TokenInfoFull({
aTokenAddress: aToken,
underlyingTokenAddress: _token,
supplyRate: t.liquidityRate,
borrowRateVariable: t.variableBorrowRate,
borrowRateStable: t.stableBorrowRate,
totalSupply: ERC20(aToken).totalSupply(),
availableLiquidity: t.availableLiquidity,
totalBorrow: t.totalVariableDebt+t.totalStableDebt,
collateralFactor: ltv,
liquidationRatio: liquidationThreshold,
price: price,
usageAsCollateralEnabled: usageAsCollateralEnabled,
borrowinEnabled: borrowinEnabled,
stableBorrowRateEnabled: stableBorrowRateEnabled
});
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _market, address _user) public view returns (LoanData memory data) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowStableAmounts: new uint[](reserves.length),
borrowVariableAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowStablePos = 0;
uint64 borrowVariablePos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i].tokenAddress;
(uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowsStable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowStablePos] = reserve;
data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth;
borrowStablePos++;
}
// Sum up debt in Eth
if (borrowsVariable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowVariablePos] = reserve;
data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth;
borrowVariablePos++;
}
}
data.ratio = uint128(getSafetyRatio(_market, _user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_market, _users[i]);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelper.sol";
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "./AaveMonitorProxy.sol";
import "./AaveSubscriptions.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../AaveSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatio.sol";
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
uint256 borrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "./SaverExchangeHelper.sol";
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./SaverExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
/// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell
/// @dev safeApprove is modified to always first set approval to 0, then to exact amount
if (_type == ActionType.SELL) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from Scp and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
writeUint256(_exData.offchainData.callData, 36, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CompoundSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/ICompoundSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxyV2 is ProxyPermission {
string public constant NAME = "AaveSubscriptionsProxyV2";
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD;
address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
import "../../DS/DSGuard.sol";
import "../../DS/DSAuth.sol";
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/OsmMom.sol";
import "../../interfaces/Osm.sol";
import "../../auth/AdminAuth.sol";
import "../../interfaces/Manager.sol";
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
pragma solidity ^0.6.0;
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
pragma solidity ^0.6.0;
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
pragma solidity ^0.6.0;
import "./DSProxy.sol";
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
//TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
} | Gets CDP info (collateral, debt) _cdpId Id of the CDP _ilk Ilk of the CDP | function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
| 380,616 |
./full_match/80001/0xB35Bd2Ec0d8e629aBd68E5f607CA13b964F7A9C0/sources/contracts/BourbonNBlockchainRewards.sol | Function allowing admin to inject rewards amount 10 6, the amount of the reward injection in USDC/ distribute rewards to token owners | function injectRewards(uint256 amount) public onlyRole(INJECTION_ROLE) {
require(amount > 0, 'Reward amount must be strictly positive');
uint256[] memory validTokenIds = getTokendIdsEligibleForRewards();
for (uint256 i = 0; i < validTokenIds.length; i++) {
address owner = dropERC721Contract.ownerOf(validTokenIds[i]);
uint256 proportionalReward = amount / validTokenIds.length;
uint256 tokenMintTimestamp = tokenMintTimestamps[validTokenIds[i]];
bool rewardForfeitable = feeContract.isTokenIdAddrForfeitable(owner, validTokenIds[i], tokenMintTimestamp);
if (rewardForfeitable) {
forfeitedBalance += proportionalReward;
balances[owner] += proportionalReward;
tokenRewardsClaimed[owner][validTokenIds[i]] += proportionalReward;
}
}
SafeERC20.safeTransferFrom(usdcContract, msg.sender, address(this), amount);
injections.push(Injection(block.timestamp, amount));
emit RewardInjected(msg.sender, amount);
}
| 5,605,789 |
/*
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-utils/contracts/src/v06/LibBytesV06.sol";
import "./migrations/LibBootstrap.sol";
import "./features/Bootstrap.sol";
import "./storage/LibProxyStorage.sol";
import "./errors/LibProxyRichErrors.sol";
/// @dev An extensible proxy contract that serves as a universal entry point for
/// interacting with the 0x protocol.
contract ZeroEx {
// solhint-disable separate-by-one-line-in-contract,indent,var-name-mixedcase
using LibBytesV06 for bytes;
/// @dev Construct this contract and register the `Bootstrap` feature.
/// After constructing this contract, `bootstrap()` should be called
/// to seed the initial feature set.
constructor() public {
// Temporarily create and register the bootstrap feature.
// It will deregister itself after `bootstrap()` has been called.
Bootstrap bootstrap = new Bootstrap(msg.sender);
LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] =
address(bootstrap);
}
// solhint-disable state-visibility
/// @dev Forwards calls to the appropriate implementation contract.
fallback() external payable {
bytes4 selector = msg.data.readBytes4(0);
address impl = getFunctionImplementation(selector);
if (impl == address(0)) {
_revertWithData(LibProxyRichErrors.NotImplementedError(selector));
}
(bool success, bytes memory resultData) = impl.delegatecall(msg.data);
if (!success) {
_revertWithData(resultData);
}
_returnWithData(resultData);
}
/// @dev Fallback for just receiving ether.
receive() external payable {}
// solhint-enable state-visibility
/// @dev Get the implementation contract of a registered function.
/// @param selector The function selector.
/// @return impl The implementation contract address.
function getFunctionImplementation(bytes4 selector)
public
view
returns (address impl)
{
return LibProxyStorage.getStorage().impls[selector];
}
/// @dev Revert with arbitrary bytes.
/// @param data Revert data.
function _revertWithData(bytes memory data) private pure {
assembly { revert(add(data, 32), mload(data)) }
}
/// @dev Return with arbitrary bytes.
/// @param data Return data.
function _returnWithData(bytes memory data) private pure {
assembly { return(add(data, 32), mload(data)) }
}
}
/*
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;
import "./errors/LibBytesRichErrorsV06.sol";
import "./errors/LibRichErrorsV06.sol";
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
/*
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;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
/*
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;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibProxyRichErrors.sol";
library LibBootstrap {
/// @dev Magic bytes returned by the bootstrapper to indicate success.
/// This is `keccack('BOOTSTRAP_SUCCESS')`.
bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b;
using LibRichErrorsV06 for bytes;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallBootstrapFunction(
address target,
bytes memory data
)
internal
{
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS)
{
LibProxyRichErrors.BootstrapCallFailedError(target, resultData).rrevert();
}
}
}
/*
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;
library LibProxyRichErrors {
// solhint-disable func-name-mixedcase
function NotImplementedError(bytes4 selector)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NotImplementedError(bytes4)")),
selector
);
}
function InvalidBootstrapCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidBootstrapCallerError(address,address)")),
actual,
expected
);
}
function InvalidDieCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidDieCallerError(address,address)")),
actual,
expected
);
}
function BootstrapCallFailedError(address target, bytes memory resultData)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BootstrapCallFailedError(address,bytes)")),
target,
resultData
);
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../migrations/LibBootstrap.sol";
import "../storage/LibProxyStorage.sol";
import "./IBootstrap.sol";
/// @dev Detachable `bootstrap()` feature.
contract Bootstrap is
IBootstrap
{
// solhint-disable state-visibility,indent
/// @dev The ZeroEx contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _deployer;
/// @dev The implementation address of this contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _implementation;
/// @dev The deployer.
/// This has to be immutable to persist across delegatecalls.
address immutable private _bootstrapCaller;
// solhint-enable state-visibility,indent
using LibRichErrorsV06 for bytes;
/// @dev Construct this contract and set the bootstrap migration contract.
/// After constructing this contract, `bootstrap()` should be called
/// to seed the initial feature set.
/// @param bootstrapCaller The allowed caller of `bootstrap()`.
constructor(address bootstrapCaller) public {
_deployer = msg.sender;
_implementation = address(this);
_bootstrapCaller = bootstrapCaller;
}
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external override {
// Only the bootstrap caller can call this function.
if (msg.sender != _bootstrapCaller) {
LibProxyRichErrors.InvalidBootstrapCallerError(
msg.sender,
_bootstrapCaller
).rrevert();
}
// Deregister.
LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0);
// Self-destruct.
Bootstrap(_implementation).die();
// Call the bootstrapper.
LibBootstrap.delegatecallBootstrapFunction(target, callData);
}
/// @dev Self-destructs this contract.
/// Can only be called by the deployer.
function die() external {
if (msg.sender != _deployer) {
LibProxyRichErrors.InvalidDieCallerError(msg.sender, _deployer).rrevert();
}
selfdestruct(msg.sender);
}
}
/*
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 "./LibStorage.sol";
/// @dev Storage helpers for the proxy contract.
library LibProxyStorage {
/// @dev Storage bucket for proxy contract.
struct Storage {
// Mapping of function selector -> function implementation
mapping(bytes4 => address) impls;
// The owner of the proxy contract.
address owner;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.Proxy
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
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;
/// @dev Common storage helpers
library LibStorage {
/// @dev What to bit-shift a storage ID by to get its slot.
/// This gives us a maximum of 2**128 inline fields in each bucket.
uint256 private constant STORAGE_SLOT_EXP = 128;
/// @dev Storage IDs for feature storage buckets.
/// WARNING: APPEND-ONLY.
enum StorageId {
Proxy,
SimpleFunctionRegistry,
Ownable,
TokenSpender,
TransformERC20
}
/// @dev Get the storage slot given a storage ID. We assign unique, well-spaced
/// slots to storage bucket variables to ensure they do not overlap.
/// See: https://solidity.readthedocs.io/en/v0.6.6/assembly.html#access-to-external-variables-functions-and-libraries
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function getStorageSlot(StorageId storageId)
internal
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return (uint256(storageId) + 1) << STORAGE_SLOT_EXP;
}
}
/*
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;
/// @dev Detachable `bootstrap()` feature.
interface IBootstrap {
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external;
}
/*
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;
library LibCommonRichErrors {
// solhint-disable func-name-mixedcase
function OnlyCallableBySelfError(address sender)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyCallableBySelfError(address)")),
sender
);
}
function IllegalReentrancyError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IllegalReentrancyError()"))
);
}
}
/*
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;
library LibOwnableRichErrors {
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOwnerError(address,address)")),
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("TransferOwnerToZeroError()"))
);
}
function MigrateCallFailedError(address target, bytes memory resultData)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("MigrateCallFailedError(address,bytes)")),
target,
resultData
);
}
}
/*
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;
library LibSimpleFunctionRegistryRichErrors {
// solhint-disable func-name-mixedcase
function NotInRollbackHistoryError(bytes4 selector, address targetImpl)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NotInRollbackHistoryError(bytes4,address)")),
selector,
targetImpl
);
}
}
/*
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;
library LibSpenderRichErrors {
// solhint-disable func-name-mixedcase
function SpenderERC20TransferFromFailedError(
address token,
address owner,
address to,
uint256 amount,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SpenderERC20TransferFromFailedError(address,address,address,uint256,bytes)")),
token,
owner,
to,
amount,
errorData
);
}
}
/*
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;
library LibTransformERC20RichErrors {
// solhint-disable func-name-mixedcase,separate-by-one-line-in-contract
function InsufficientEthAttachedError(
uint256 ethAttached,
uint256 ethNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientEthAttachedError(uint256,uint256)")),
ethAttached,
ethNeeded
);
}
function IncompleteTransformERC20Error(
address outputToken,
uint256 outputTokenAmount,
uint256 minOutputTokenAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteTransformERC20Error(address,uint256,uint256)")),
outputToken,
outputTokenAmount,
minOutputTokenAmount
);
}
function NegativeTransformERC20OutputError(
address outputToken,
uint256 outputTokenLostAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NegativeTransformERC20OutputError(address,uint256)")),
outputToken,
outputTokenLostAmount
);
}
function TransformerFailedError(
address transformer,
bytes memory transformerData,
bytes memory resultData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("TransformerFailedError(address,bytes,bytes)")),
transformer,
transformerData,
resultData
);
}
// Common Transformer errors ///////////////////////////////////////////////
function OnlyCallableByDeployerError(
address caller,
address deployer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyCallableByDeployerError(address,address)")),
caller,
deployer
);
}
function InvalidExecutionContextError(
address actualContext,
address expectedContext
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidExecutionContextError(address,address)")),
actualContext,
expectedContext
);
}
enum InvalidTransformDataErrorCode {
INVALID_TOKENS,
INVALID_ARRAY_LENGTH
}
function InvalidTransformDataError(
InvalidTransformDataErrorCode errorCode,
bytes memory transformData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidTransformDataError(uint8,bytes)")),
errorCode,
transformData
);
}
// FillQuoteTransformer errors /////////////////////////////////////////////
function IncompleteFillSellQuoteError(
address sellToken,
uint256 soldAmount,
uint256 sellAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteFillSellQuoteError(address,uint256,uint256)")),
sellToken,
soldAmount,
sellAmount
);
}
function IncompleteFillBuyQuoteError(
address buyToken,
uint256 boughtAmount,
uint256 buyAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteFillBuyQuoteError(address,uint256,uint256)")),
buyToken,
boughtAmount,
buyAmount
);
}
function InsufficientTakerTokenError(
uint256 tokenBalance,
uint256 tokensNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientTakerTokenError(uint256,uint256)")),
tokenBalance,
tokensNeeded
);
}
function InsufficientProtocolFeeError(
uint256 ethBalance,
uint256 ethNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientProtocolFeeError(uint256,uint256)")),
ethBalance,
ethNeeded
);
}
function InvalidERC20AssetDataError(
bytes memory assetData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidERC20AssetDataError(bytes)")),
assetData
);
}
function InvalidTakerFeeTokenError(
address token
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidTakerFeeTokenError(address)")),
token
);
}
}
/*
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;
library LibWalletRichErrors {
// solhint-disable func-name-mixedcase
function WalletExecuteCallFailedError(
address wallet,
address callTarget,
bytes memory callData,
uint256 callValue,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("WalletExecuteCallFailedError(address,address,bytes,uint256,bytes)")),
wallet,
callTarget,
callData,
callValue,
errorData
);
}
function WalletExecuteDelegateCallFailedError(
address wallet,
address callTarget,
bytes memory callData,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("WalletExecuteDelegateCallFailedError(address,address,bytes,bytes)")),
wallet,
callTarget,
callData,
errorData
);
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol";
import "../errors/LibSpenderRichErrors.sol";
import "./IAllowanceTarget.sol";
/// @dev The allowance target for the TokenSpender feature.
contract AllowanceTarget is
IAllowanceTarget,
AuthorizableV06
{
// solhint-disable no-unused-vars,indent,no-empty-blocks
using LibRichErrorsV06 for bytes;
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData
)
external
override
onlyAuthorized
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.call(callData);
if (!success) {
resultData.rrevert();
}
}
}
/*
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;
import "./interfaces/IAuthorizableV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibAuthorizableRichErrorsV06.sol";
import "./OwnableV06.sol";
// solhint-disable no-empty-blocks
contract AuthorizableV06 is
OwnableV06,
IAuthorizableV06
{
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
_assertSenderIsAuthorized();
_;
}
// @dev Whether an address is authorized to call privileged functions.
// @param 0 Address to query.
// @return 0 Whether the address is authorized.
mapping (address => bool) public override authorized;
// @dev Whether an address is authorized to call privileged functions.
// @param 0 Index of authorized address.
// @return 0 Authorized address.
address[] public override authorities;
/// @dev Initializes the `owner` address.
constructor()
public
OwnableV06()
{}
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external
override
onlyOwner
{
_addAuthorizedAddress(target);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external
override
onlyOwner
{
if (!authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target));
}
for (uint256 i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
_removeAuthorizedAddressAtIndex(target, i);
break;
}
}
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external
override
onlyOwner
{
_removeAuthorizedAddressAtIndex(target, index);
}
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
external
override
view
returns (address[] memory)
{
return authorities;
}
/// @dev Reverts if msg.sender is not authorized.
function _assertSenderIsAuthorized()
internal
view
{
if (!authorized[msg.sender]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.SenderNotAuthorizedError(msg.sender));
}
}
/// @dev Authorizes an address.
/// @param target Address to authorize.
function _addAuthorizedAddress(address target)
internal
{
// Ensure that the target is not the zero address.
if (target == address(0)) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.ZeroCantBeAuthorizedError());
}
// Ensure that the target is not already authorized.
if (authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetAlreadyAuthorizedError(target));
}
authorized[target] = true;
authorities.push(target);
emit AuthorizedAddressAdded(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function _removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
internal
{
if (!authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target));
}
if (index >= authorities.length) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.IndexOutOfBoundsError(
index,
authorities.length
));
}
if (authorities[index] != target) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.AuthorizedAddressMismatchError(
authorities[index],
target
));
}
delete authorized[target];
authorities[index] = authorities[authorities.length - 1];
authorities.pop();
emit AuthorizedAddressRemoved(target, msg.sender);
}
}
/*
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;
import "./IOwnableV06.sol";
interface IAuthorizableV06 is
IOwnableV06
{
// Event logged when a new address is authorized.
event AuthorizedAddressAdded(
address indexed target,
address indexed caller
);
// Event logged when a currently authorized address is unauthorized.
event AuthorizedAddressRemoved(
address indexed target,
address indexed caller
);
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external;
/// @dev Gets all authorized addresses.
/// @return authorizedAddresses Array of authorized addresses.
function getAuthorizedAddresses()
external
view
returns (address[] memory authorizedAddresses);
/// @dev Whether an adderss is authorized to call privileged functions.
/// @param addr Address to query.
/// @return isAuthorized Whether the address is authorized.
function authorized(address addr) external view returns (bool isAuthorized);
/// @dev All addresseses authorized to call privileged functions.
/// @param idx Index of authorized address.
/// @return addr Authorized address.
function authorities(uint256 idx) external view returns (address addr);
}
/*
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;
interface IOwnableV06 {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner) external;
/// @dev The owner of this contract.
/// @return ownerAddress The owner address.
function owner() external view returns (address ownerAddress);
}
/*
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;
library LibAuthorizableRichErrorsV06 {
// bytes4(keccak256("AuthorizedAddressMismatchError(address,address)"))
bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR =
0x140a84db;
// bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)"))
bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR =
0xe9f83771;
// bytes4(keccak256("SenderNotAuthorizedError(address)"))
bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR =
0xb65a25b9;
// bytes4(keccak256("TargetAlreadyAuthorizedError(address)"))
bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR =
0xde16f1a0;
// bytes4(keccak256("TargetNotAuthorizedError(address)"))
bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR =
0xeb5108a2;
// bytes4(keccak256("ZeroCantBeAuthorizedError()"))
bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES =
hex"57654fe4";
// solhint-disable func-name-mixedcase
function AuthorizedAddressMismatchError(
address authorized,
address target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR,
authorized,
target
);
}
function IndexOutOfBoundsError(
uint256 index,
uint256 length
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR,
index,
length
);
}
function SenderNotAuthorizedError(address sender)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SENDER_NOT_AUTHORIZED_ERROR_SELECTOR,
sender
);
}
function TargetAlreadyAuthorizedError(address target)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR,
target
);
}
function TargetNotAuthorizedError(address target)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TARGET_NOT_AUTHORIZED_ERROR_SELECTOR,
target
);
}
function ZeroCantBeAuthorizedError()
internal
pure
returns (bytes memory)
{
return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES;
}
}
/*
Copyright 2019 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;
import "./interfaces/IOwnableV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibOwnableRichErrorsV06.sol";
contract OwnableV06 is
IOwnableV06
{
/// @dev The owner of this contract.
/// @return 0 The owner address.
address public override owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
_assertSenderIsOwner();
_;
}
/// @dev Change the owner of this contract.
/// @param newOwner New owner address.
function transferOwnership(address newOwner)
public
override
onlyOwner
{
if (newOwner == address(0)) {
LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.TransferOwnerToZeroError());
} else {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
function _assertSenderIsOwner()
internal
view
{
if (msg.sender != owner) {
LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
));
}
}
}
/*
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;
library LibOwnableRichErrorsV06 {
// bytes4(keccak256("OnlyOwnerError(address,address)"))
bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
0x1de45ad1;
// bytes4(keccak256("TransferOwnerToZeroError()"))
bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
hex"e69edc3e";
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ONLY_OWNER_ERROR_SELECTOR,
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
}
}
/*
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-utils/contracts/src/v06/interfaces/IAuthorizableV06.sol";
/// @dev The allowance target for the TokenSpender feature.
interface IAllowanceTarget is
IAuthorizableV06
{
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData
)
external
returns (bytes memory resultData);
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol";
import "../errors/LibWalletRichErrors.sol";
import "./IFlashWallet.sol";
/// @dev A contract that can execute arbitrary calls from its owner.
contract FlashWallet is
IFlashWallet
{
// solhint-disable no-unused-vars,indent,no-empty-blocks
using LibRichErrorsV06 for bytes;
// solhint-disable
/// @dev Store the owner/deployer as an immutable to make this contract stateless.
address public override immutable owner;
// solhint-enable
constructor() public {
// The deployer is the owner.
owner = msg.sender;
}
/// @dev Allows only the (immutable) owner to call a function.
modifier onlyOwner() virtual {
if (msg.sender != owner) {
LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
_;
}
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @param value Ether to attach to the call.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData,
uint256 value
)
external
payable
override
onlyOwner
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.call{value: value}(callData);
if (!success) {
LibWalletRichErrors
.WalletExecuteCallFailedError(
address(this),
target,
callData,
value,
resultData
)
.rrevert();
}
}
/// @dev Execute an arbitrary delegatecall, in the context of this puppet.
/// Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeDelegateCall(
address payable target,
bytes calldata callData
)
external
payable
override
onlyOwner
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.delegatecall(callData);
if (!success) {
LibWalletRichErrors
.WalletExecuteDelegateCallFailedError(
address(this),
target,
callData,
resultData
)
.rrevert();
}
}
// solhint-disable
/// @dev Allows this contract to receive ether.
receive() external override payable {}
// solhint-enable
/// @dev Signal support for receiving ERC1155 tokens.
/// @param interfaceID The interface ID, as per ERC-165 rules.
/// @return hasSupport `true` if this contract supports an ERC-165 interface.
function supportsInterface(bytes4 interfaceID)
external
pure
returns (bool hasSupport)
{
return interfaceID == this.supportsInterface.selector ||
interfaceID == this.onERC1155Received.selector ^ this.onERC1155BatchReceived.selector ||
interfaceID == this.tokenFallback.selector;
}
/// @dev Allow this contract to receive ERC1155 tokens.
/// @return success `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155Received(
address, // operator,
address, // from,
uint256, // id,
uint256, // value,
bytes calldata //data
)
external
pure
returns (bytes4 success)
{
return this.onERC1155Received.selector;
}
/// @dev Allow this contract to receive ERC1155 tokens.
/// @return success `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
function onERC1155BatchReceived(
address, // operator,
address, // from,
uint256[] calldata, // ids,
uint256[] calldata, // values,
bytes calldata // data
)
external
pure
returns (bytes4 success)
{
return this.onERC1155BatchReceived.selector;
}
/// @dev Allows this contract to receive ERC223 tokens.
function tokenFallback(
address, // from,
uint256, // value,
bytes calldata // value
)
external
pure
{}
}
/*
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-utils/contracts/src/v06/interfaces/IOwnableV06.sol";
/// @dev A contract that can execute arbitrary calls from its owner.
interface IFlashWallet {
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @param value Ether to attach to the call.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData,
uint256 value
)
external
payable
returns (bytes memory resultData);
/// @dev Execute an arbitrary delegatecall, in the context of this puppet.
/// Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeDelegateCall(
address payable target,
bytes calldata callData
)
external
payable
returns (bytes memory resultData);
/// @dev Allows the puppet to receive ETH.
receive() external payable;
/// @dev Fetch the immutable owner/deployer of this contract.
/// @return owner_ The immutable owner/deployer/
function owner() external view returns (address owner_);
}
/*
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-utils/contracts/src/v06/AuthorizableV06.sol";
/// @dev A contract with a `die()` function.
interface IKillable {
function die() external;
}
/// @dev Deployer contract for ERC20 transformers.
/// Only authorities may call `deploy()` and `kill()`.
contract TransformerDeployer is
AuthorizableV06
{
/// @dev Emitted when a contract is deployed via `deploy()`.
/// @param deployedAddress The address of the deployed contract.
/// @param nonce The deployment nonce.
/// @param sender The caller of `deploy()`.
event Deployed(address deployedAddress, uint256 nonce, address sender);
/// @dev Emitted when a contract is killed via `kill()`.
/// @param target The address of the contract being killed..
/// @param sender The caller of `kill()`.
event Killed(address target, address sender);
// @dev The current nonce of this contract.
uint256 public nonce = 1;
// @dev Mapping of deployed contract address to deployment nonce.
mapping (address => uint256) public toDeploymentNonce;
/// @dev Create this contract and register authorities.
constructor(address[] memory authorities) public {
for (uint256 i = 0; i < authorities.length; ++i) {
_addAuthorizedAddress(authorities[i]);
}
}
/// @dev Deploy a new contract. Only callable by an authority.
/// Any attached ETH will also be forwarded.
function deploy(bytes memory bytecode)
public
payable
onlyAuthorized
returns (address deployedAddress)
{
uint256 deploymentNonce = nonce;
nonce += 1;
assembly {
deployedAddress := create(callvalue(), add(bytecode, 32), mload(bytecode))
}
toDeploymentNonce[deployedAddress] = deploymentNonce;
emit Deployed(deployedAddress, deploymentNonce, msg.sender);
}
/// @dev Call `die()` on a contract. Only callable by an authority.
function kill(IKillable target)
public
onlyAuthorized
{
target.die();
emit Killed(address(target), msg.sender);
}
}
/*
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;
/// @dev Basic interface for a feature contract.
interface IFeature {
// solhint-disable func-name-mixedcase
/// @dev The name of this feature set.
function FEATURE_NAME() external view returns (string memory name);
/// @dev The version of this feature set.
function FEATURE_VERSION() external view returns (uint256 version);
}
/*
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-utils/contracts/src/v06/interfaces/IOwnableV06.sol";
// solhint-disable no-empty-blocks
/// @dev Owner management and migration features.
interface IOwnable is
IOwnableV06
{
/// @dev Emitted when `migrate()` is called.
/// @param caller The caller of `migrate()`.
/// @param migrator The migration contract.
/// @param newOwner The address of the new owner.
event Migrated(address caller, address migrator, address newOwner);
/// @dev Execute a migration function in the context of the ZeroEx contract.
/// The result of the function being called should be the magic bytes
/// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner.
/// The owner will be temporarily set to `address(this)` inside the call.
/// Before returning, the owner will be set to `newOwner`.
/// @param target The migrator contract address.
/// @param newOwner The address of the new owner.
/// @param data The call data.
function migrate(address target, bytes calldata data, address newOwner) external;
}
/*
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;
/// @dev Basic registry management features.
interface ISimpleFunctionRegistry {
/// @dev A function implementation was updated via `extend()` or `rollback()`.
/// @param selector The function selector.
/// @param oldImpl The implementation contract address being replaced.
/// @param newImpl The replacement implementation contract address.
event ProxyFunctionUpdated(bytes4 indexed selector, address oldImpl, address newImpl);
/// @dev Roll back to a prior implementation of a function.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl) external;
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl) external;
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector)
external
view
returns (uint256 rollbackLength);
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
view
returns (address impl);
}
/*
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";
/// @dev Feature that allows spending token allowances.
interface ITokenSpender {
/// @dev Transfers ERC20 tokens from `owner` to `to`.
/// Only callable from within.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _spendERC20Tokens(
IERC20TokenV06 token,
address owner,
address to,
uint256 amount
)
external;
/// @dev Gets the maximum amount of an ERC20 token `token` that can be
/// pulled from `owner`.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @return amount The amount of tokens that can be pulled.
function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner)
external
view
returns (uint256 amount);
/// @dev Get the address of the allowance target.
/// @return target The target of token allowances.
function getAllowanceTarget() external view returns (address target);
}
/*
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;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
/*
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 "../transformers/IERC20Transformer.sol";
import "../external/IFlashWallet.sol";
/// @dev Feature to composably transform between ERC20 tokens.
interface ITransformERC20 {
/// @dev Defines a transformation to run in `transformERC20()`.
struct Transformation {
// The deployment nonce for the transformer.
// The address of the transformer contract will be derived from this
// value.
uint32 deploymentNonce;
// Arbitrary data to pass to the transformer.
bytes data;
}
/// @dev Raised upon a successful `transformERC20`.
/// @param taker The taker (caller) address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// @param outputTokenAmount The amount of `outputToken` received by the taker.
event TransformedERC20(
address indexed taker,
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount
);
/// @dev Raised when `setTransformerDeployer()` is called.
/// @param transformerDeployer The new deployer address.
event TransformerDeployerUpdated(address transformerDeployer);
/// @dev Replace the allowed deployer for transformers.
/// Only callable by the owner.
/// @param transformerDeployer The address of the trusted deployer for transformers.
function setTransformerDeployer(address transformerDeployer)
external;
/// @dev Deploy a new flash wallet instance and replace the current one with it.
/// Useful if we somehow break the current wallet instance.
/// Anyone can call this.
/// @return wallet The new wallet instance.
function createTransformWallet()
external
returns (IFlashWallet wallet);
/// @dev Executes a series of transformations to convert an ERC20 `inputToken`
/// to an ERC20 `outputToken`.
/// @param inputToken The token being provided by the sender.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the sender.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the sender.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the sender
/// must receive for the entire transformation to succeed.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the sender.
function transformERC20(
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] calldata transformations
)
external
payable
returns (uint256 outputTokenAmount);
/// @dev Internal version of `transformERC20()`. Only callable from within.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] calldata transformations
)
external
payable
returns (uint256 outputTokenAmount);
/// @dev Return the current wallet instance that will serve as the execution
/// context for transformations.
/// @return wallet The wallet instance.
function getTransformWallet()
external
view
returns (IFlashWallet wallet);
/// @dev Return the allowed deployer for transformers.
/// @return deployer The transform deployer address.
function getTransformerDeployer()
external
view
returns (address deployer);
}
/*
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";
/// @dev A transformation callback used in `TransformERC20.transformERC20()`.
interface IERC20Transformer {
/// @dev Called from `TransformERC20.transformERC20()`. This will be
/// delegatecalled in the context of the FlashWallet instance being used.
/// @param callDataHash The hash of the `TransformERC20.transformERC20()` calldata.
/// @param taker The taker address (caller of `TransformERC20.transformERC20()`).
/// @param data Arbitrary data to pass to the transformer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32 callDataHash,
address payable taker,
bytes calldata data
)
external
returns (bytes4 success);
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../fixins/FixinCommon.sol";
import "../errors/LibOwnableRichErrors.sol";
import "../storage/LibOwnableStorage.sol";
import "../migrations/LibBootstrap.sol";
import "../migrations/LibMigrate.sol";
import "./IFeature.sol";
import "./IOwnable.sol";
import "./SimpleFunctionRegistry.sol";
/// @dev Owner management features.
contract Ownable is
IFeature,
IOwnable,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "Ownable";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The deployed address of this contract.
address immutable private _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initializes this feature. The intial owner will be set to this (ZeroEx)
/// to allow the bootstrappers to call `extend()`. Ownership should be
/// transferred to the real owner by the bootstrapper after
/// bootstrapping is complete.
/// @return success Magic bytes if successful.
function bootstrap() external returns (bytes4 success) {
// Set the owner to ourselves to allow bootstrappers to call `extend()`.
LibOwnableStorage.getStorage().owner = address(this);
// Register feature functions.
SimpleFunctionRegistry(address(this))._extendSelf(this.transferOwnership.selector, _implementation);
SimpleFunctionRegistry(address(this))._extendSelf(this.owner.selector, _implementation);
SimpleFunctionRegistry(address(this))._extendSelf(this.migrate.selector, _implementation);
return LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Change the owner of this contract.
/// Only directly callable by the owner.
/// @param newOwner New owner address.
function transferOwnership(address newOwner)
external
override
onlyOwner
{
LibOwnableStorage.Storage storage proxyStor = LibOwnableStorage.getStorage();
if (newOwner == address(0)) {
LibOwnableRichErrors.TransferOwnerToZeroError().rrevert();
} else {
proxyStor.owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
/// @dev Execute a migration function in the context of the ZeroEx contract.
/// The result of the function being called should be the magic bytes
/// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner.
/// Temporarily sets the owner to ourselves so we can perform admin functions.
/// Before returning, the owner will be set to `newOwner`.
/// @param target The migrator contract address.
/// @param data The call data.
/// @param newOwner The address of the new owner.
function migrate(address target, bytes calldata data, address newOwner)
external
override
onlyOwner
{
if (newOwner == address(0)) {
LibOwnableRichErrors.TransferOwnerToZeroError().rrevert();
}
LibOwnableStorage.Storage storage stor = LibOwnableStorage.getStorage();
// The owner will be temporarily set to `address(this)` inside the call.
stor.owner = address(this);
// Perform the migration.
LibMigrate.delegatecallMigrateFunction(target, data);
// Update the owner.
stor.owner = newOwner;
emit Migrated(msg.sender, target, newOwner);
}
/// @dev Get the owner of this contract.
/// @return owner_ The owner of this contract.
function owner() external override view returns (address owner_) {
return LibOwnableStorage.getStorage().owner;
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibCommonRichErrors.sol";
import "../errors/LibOwnableRichErrors.sol";
import "../features/IOwnable.sol";
/// @dev Common feature utilities.
contract FixinCommon {
using LibRichErrorsV06 for bytes;
/// @dev The caller must be this contract.
modifier onlySelf() virtual {
if (msg.sender != address(this)) {
LibCommonRichErrors.OnlyCallableBySelfError(msg.sender).rrevert();
}
_;
}
/// @dev The caller of this function must be the owner.
modifier onlyOwner() virtual {
{
address owner = IOwnable(address(this)).owner();
if (msg.sender != owner) {
LibOwnableRichErrors.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
}
_;
}
/// @dev Encode a feature version as a `uint256`.
/// @param major The major version number of the feature.
/// @param minor The minor version number of the feature.
/// @param revision The revision number of the feature.
/// @return encodedVersion The encoded version number.
function _encodeVersion(uint32 major, uint32 minor, uint32 revision)
internal
pure
returns (uint256 encodedVersion)
{
return (major << 64) | (minor << 32) | revision;
}
}
/*
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 "./LibStorage.sol";
/// @dev Storage helpers for the `Ownable` feature.
library LibOwnableStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// The owner of this contract.
address owner;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.Ownable
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibOwnableRichErrors.sol";
library LibMigrate {
/// @dev Magic bytes returned by a migrator to indicate success.
/// This is `keccack('MIGRATE_SUCCESS')`.
bytes4 internal constant MIGRATE_SUCCESS = 0x2c64c5ef;
using LibRichErrorsV06 for bytes;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallMigrateFunction(
address target,
bytes memory data
)
internal
{
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != MIGRATE_SUCCESS)
{
LibOwnableRichErrors.MigrateCallFailedError(target, resultData).rrevert();
}
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../fixins/FixinCommon.sol";
import "../storage/LibProxyStorage.sol";
import "../storage/LibSimpleFunctionRegistryStorage.sol";
import "../errors/LibSimpleFunctionRegistryRichErrors.sol";
import "../migrations/LibBootstrap.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Basic registry management features.
contract SimpleFunctionRegistry is
IFeature,
ISimpleFunctionRegistry,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "SimpleFunctionRegistry";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The deployed address of this contract.
address private immutable _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initializes this feature, registering its own functions.
/// @return success Magic bytes if successful.
function bootstrap()
external
returns (bytes4 success)
{
// Register the registration functions (inception vibes).
_extend(this.extend.selector, _implementation);
_extend(this._extendSelf.selector, _implementation);
// Register the rollback function.
_extend(this.rollback.selector, _implementation);
// Register getters.
_extend(this.getRollbackLength.selector, _implementation);
_extend(this.getRollbackEntryAtIndex.selector, _implementation);
return LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Roll back to a prior implementation of a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl)
external
override
onlyOwner
{
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address currentImpl = proxyStor.impls[selector];
if (currentImpl == targetImpl) {
// Do nothing if already at targetImpl.
return;
}
// Walk history backwards until we find the target implementation.
address[] storage history = stor.implHistory[selector];
uint256 i = history.length;
for (; i > 0; --i) {
address impl = history[i - 1];
history.pop();
if (impl == targetImpl) {
break;
}
}
if (i == 0) {
LibSimpleFunctionRegistryRichErrors.NotInRollbackHistoryError(
selector,
targetImpl
).rrevert();
}
proxyStor.impls[selector] = targetImpl;
emit ProxyFunctionUpdated(selector, currentImpl, targetImpl);
}
/// @dev Register or replace a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl)
external
override
onlyOwner
{
_extend(selector, impl);
}
/// @dev Register or replace a function.
/// Only callable from within.
/// This function is only used during the bootstrap process and
/// should be deregistered by the deployer after bootstrapping is
/// complete.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extendSelf(bytes4 selector, address impl)
external
onlySelf
{
_extend(selector, impl);
}
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector)
external
override
view
returns (uint256 rollbackLength)
{
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length;
}
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
override
view
returns (address impl)
{
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector][idx];
}
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extend(bytes4 selector, address impl)
private
{
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address oldImpl = proxyStor.impls[selector];
address[] storage history = stor.implHistory[selector];
history.push(oldImpl);
proxyStor.impls[selector] = impl;
emit ProxyFunctionUpdated(selector, oldImpl, impl);
}
/// @dev Get the storage buckets for this feature and the proxy.
/// @return stor Storage bucket for this feature.
/// @return proxyStor age bucket for the proxy.
function _getStorages()
private
pure
returns (
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
)
{
return (
LibSimpleFunctionRegistryStorage.getStorage(),
LibProxyStorage.getStorage()
);
}
}
/*
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 "./LibStorage.sol";
/// @dev Storage helpers for the `SimpleFunctionRegistry` feature.
library LibSimpleFunctionRegistryStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// Mapping of function selector -> implementation history.
mapping(bytes4 => address[]) implHistory;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.SimpleFunctionRegistry
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibSpenderRichErrors.sol";
import "../fixins/FixinCommon.sol";
import "../migrations/LibMigrate.sol";
import "../external/IAllowanceTarget.sol";
import "../storage/LibTokenSpenderStorage.sol";
import "./ITokenSpender.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Feature that allows spending token allowances.
contract TokenSpender is
IFeature,
ITokenSpender,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "TokenSpender";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The implementation address of this feature.
address private immutable _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initialize and register this feature. Should be delegatecalled
/// into during a `Migrate.migrate()`.
/// @param allowanceTarget An `allowanceTarget` instance, configured to have
/// the ZeroeEx contract as an authority.
/// @return success `MIGRATE_SUCCESS` on success.
function migrate(IAllowanceTarget allowanceTarget) external returns (bytes4 success) {
LibTokenSpenderStorage.getStorage().allowanceTarget = allowanceTarget;
ISimpleFunctionRegistry(address(this))
.extend(this.getAllowanceTarget.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this._spendERC20Tokens.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.getSpendableERC20BalanceOf.selector, _implementation);
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Transfers ERC20 tokens from `owner` to `to`. Only callable from within.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _spendERC20Tokens(
IERC20TokenV06 token,
address owner,
address to,
uint256 amount
)
external
override
onlySelf
{
IAllowanceTarget spender = LibTokenSpenderStorage.getStorage().allowanceTarget;
// Have the allowance target execute an ERC20 `transferFrom()`.
(bool didSucceed, bytes memory resultData) = address(spender).call(
abi.encodeWithSelector(
IAllowanceTarget.executeCall.selector,
address(token),
abi.encodeWithSelector(
IERC20TokenV06.transferFrom.selector,
owner,
to,
amount
)
)
);
if (didSucceed) {
resultData = abi.decode(resultData, (bytes));
}
if (!didSucceed || !LibERC20TokenV06.isSuccessfulResult(resultData)) {
LibSpenderRichErrors.SpenderERC20TransferFromFailedError(
address(token),
owner,
to,
amount,
resultData
).rrevert();
}
}
/// @dev Gets the maximum amount of an ERC20 token `token` that can be
/// pulled from `owner` by the token spender.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @return amount The amount of tokens that can be pulled.
function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner)
external
override
view
returns (uint256 amount)
{
return LibSafeMathV06.min256(
token.allowance(owner, address(LibTokenSpenderStorage.getStorage().allowanceTarget)),
token.balanceOf(owner)
);
}
/// @dev Get the address of the allowance target.
/// @return target The target of token allowances.
function getAllowanceTarget()
external
override
view
returns (address target)
{
return address(LibTokenSpenderStorage.getStorage().allowanceTarget);
}
}
/*
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;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
/*
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;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
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;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "./IERC20TokenV06.sol";
library LibERC20TokenV06 {
bytes constant private DECIMALS_CALL_DATA = hex"313ce567";
/// @dev Calls `IERC20TokenV06(token).approve()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param allowance The allowance to set.
function compatApprove(
IERC20TokenV06 token,
address spender,
uint256 allowance
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.approve.selector,
spender,
allowance
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Calls `IERC20TokenV06(token).approve()` and sets the allowance to the
/// maximum if the current approval is not already >= an amount.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param amount The minimum allowance needed.
function approveIfBelow(
IERC20TokenV06 token,
address spender,
uint256 amount
)
internal
{
if (token.allowance(address(this), spender) < amount) {
compatApprove(token, spender, uint256(-1));
}
}
/// @dev Calls `IERC20TokenV06(token).transfer()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function compatTransfer(
IERC20TokenV06 token,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.transfer.selector,
to,
amount
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Calls `IERC20TokenV06(token).transferFrom()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param from The owner of the tokens.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function compatTransferFrom(
IERC20TokenV06 token,
address from,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.transferFrom.selector,
from,
to,
amount
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Retrieves the number of decimals for a token.
/// Returns `18` if the call reverts.
/// @param token The address of the token contract.
/// @return tokenDecimals The number of decimals places for the token.
function compatDecimals(IERC20TokenV06 token)
internal
view
returns (uint8 tokenDecimals)
{
tokenDecimals = 18;
(bool didSucceed, bytes memory resultData) = address(token).staticcall(DECIMALS_CALL_DATA);
if (didSucceed && resultData.length == 32) {
tokenDecimals = uint8(LibBytesV06.readUint256(resultData, 0));
}
}
/// @dev Retrieves the allowance for a token, owner, and spender.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @param spender The address the spender.
/// @return allowance_ The allowance for a token, owner, and spender.
function compatAllowance(IERC20TokenV06 token, address owner, address spender)
internal
view
returns (uint256 allowance_)
{
(bool didSucceed, bytes memory resultData) = address(token).staticcall(
abi.encodeWithSelector(
token.allowance.selector,
owner,
spender
)
);
if (didSucceed && resultData.length == 32) {
allowance_ = LibBytesV06.readUint256(resultData, 0);
}
}
/// @dev Retrieves the balance for a token owner.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @return balance The token balance of an owner.
function compatBalanceOf(IERC20TokenV06 token, address owner)
internal
view
returns (uint256 balance)
{
(bool didSucceed, bytes memory resultData) = address(token).staticcall(
abi.encodeWithSelector(
token.balanceOf.selector,
owner
)
);
if (didSucceed && resultData.length == 32) {
balance = LibBytesV06.readUint256(resultData, 0);
}
}
/// @dev Check if the data returned by a non-static call to an ERC20 token
/// is a successful result. Supported functions are `transfer()`,
/// `transferFrom()`, and `approve()`.
/// @param resultData The raw data returned by a non-static call to the ERC20 token.
/// @return isSuccessful Whether the result data indicates success.
function isSuccessfulResult(bytes memory resultData)
internal
pure
returns (bool isSuccessful)
{
if (resultData.length == 0) {
return true;
}
if (resultData.length == 32) {
uint256 result = LibBytesV06.readUint256(resultData, 0);
if (result == 1) {
return true;
}
}
}
/// @dev Executes a call on address `target` with calldata `callData`
/// and asserts that either nothing was returned or a single boolean
/// was returned equal to `true`.
/// @param target The call target.
/// @param callData The abi-encoded call data.
function _callWithOptionalBooleanResult(
address target,
bytes memory callData
)
private
{
(bool didSucceed, bytes memory resultData) = target.call(callData);
if (didSucceed && isSuccessfulResult(resultData)) {
return;
}
LibRichErrorsV06.rrevert(resultData);
}
}
/*
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 "./LibStorage.sol";
import "../external/IAllowanceTarget.sol";
/// @dev Storage helpers for the `TokenSpender` feature.
library LibTokenSpenderStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// Allowance target contract.
IAllowanceTarget allowanceTarget;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.TokenSpender
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
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/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "../fixins/FixinCommon.sol";
import "../migrations/LibMigrate.sol";
import "../external/IFlashWallet.sol";
import "../external/FlashWallet.sol";
import "../storage/LibTransformERC20Storage.sol";
import "../transformers/IERC20Transformer.sol";
import "../transformers/LibERC20Transformer.sol";
import "./ITransformERC20.sol";
import "./ITokenSpender.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Feature to composably transform between ERC20 tokens.
contract TransformERC20 is
IFeature,
ITransformERC20,
FixinCommon
{
/// @dev Stack vars for `_transformERC20Private()`.
struct TransformERC20PrivateState {
IFlashWallet wallet;
address transformerDeployer;
uint256 takerOutputTokenBalanceBefore;
uint256 takerOutputTokenBalanceAfter;
}
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "TransformERC20";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The implementation address of this feature.
address private immutable _implementation;
// solhint-enable
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initialize and register this feature.
/// Should be delegatecalled by `Migrate.migrate()`.
/// @param transformerDeployer The trusted deployer for transformers.
/// @return success `LibMigrate.SUCCESS` on success.
function migrate(address transformerDeployer) external returns (bytes4 success) {
ISimpleFunctionRegistry(address(this))
.extend(this.getTransformerDeployer.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.createTransformWallet.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.getTransformWallet.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.setTransformerDeployer.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.transformERC20.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this._transformERC20.selector, _implementation);
createTransformWallet();
LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer;
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Replace the allowed deployer for transformers.
/// Only callable by the owner.
/// @param transformerDeployer The address of the trusted deployer for transformers.
function setTransformerDeployer(address transformerDeployer)
external
override
onlyOwner
{
LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer;
emit TransformerDeployerUpdated(transformerDeployer);
}
/// @dev Return the allowed deployer for transformers.
/// @return deployer The transform deployer address.
function getTransformerDeployer()
public
override
view
returns (address deployer)
{
return LibTransformERC20Storage.getStorage().transformerDeployer;
}
/// @dev Deploy a new wallet instance and replace the current one with it.
/// Useful if we somehow break the current wallet instance.
/// Anyone can call this.
/// @return wallet The new wallet instance.
function createTransformWallet()
public
override
returns (IFlashWallet wallet)
{
wallet = new FlashWallet();
LibTransformERC20Storage.getStorage().wallet = wallet;
}
/// @dev Executes a series of transformations to convert an ERC20 `inputToken`
/// to an ERC20 `outputToken`.
/// @param inputToken The token being provided by the sender.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the sender.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the sender.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the sender
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the sender.
function transformERC20(
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
public
override
payable
returns (uint256 outputTokenAmount)
{
return _transformERC20Private(
keccak256(msg.data),
msg.sender,
inputToken,
outputToken,
inputTokenAmount,
minOutputTokenAmount,
transformations
);
}
/// @dev Internal version of `transformERC20()`. Only callable from within.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
public
override
payable
onlySelf
returns (uint256 outputTokenAmount)
{
return _transformERC20Private(
callDataHash,
taker,
inputToken,
outputToken,
inputTokenAmount,
minOutputTokenAmount,
transformations
);
}
/// @dev Private version of `transformERC20()`.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20Private(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
private
returns (uint256 outputTokenAmount)
{
// If the input token amount is -1, transform the taker's entire
// spendable balance.
if (inputTokenAmount == uint256(-1)) {
inputTokenAmount = ITokenSpender(address(this))
.getSpendableERC20BalanceOf(inputToken, taker);
}
TransformERC20PrivateState memory state;
state.wallet = getTransformWallet();
state.transformerDeployer = getTransformerDeployer();
// Remember the initial output token balance of the taker.
state.takerOutputTokenBalanceBefore =
LibERC20Transformer.getTokenBalanceOf(outputToken, taker);
// Pull input tokens from the taker to the wallet and transfer attached ETH.
_transferInputTokensAndAttachedEth(
inputToken,
taker,
address(state.wallet),
inputTokenAmount
);
// Perform transformations.
for (uint256 i = 0; i < transformations.length; ++i) {
_executeTransformation(
state.wallet,
transformations[i],
state.transformerDeployer,
taker,
callDataHash
);
}
// Compute how much output token has been transferred to the taker.
state.takerOutputTokenBalanceAfter =
LibERC20Transformer.getTokenBalanceOf(outputToken, taker);
if (state.takerOutputTokenBalanceAfter > state.takerOutputTokenBalanceBefore) {
outputTokenAmount = state.takerOutputTokenBalanceAfter.safeSub(
state.takerOutputTokenBalanceBefore
);
} else if (state.takerOutputTokenBalanceAfter < state.takerOutputTokenBalanceBefore) {
LibTransformERC20RichErrors.NegativeTransformERC20OutputError(
address(outputToken),
state.takerOutputTokenBalanceBefore - state.takerOutputTokenBalanceAfter
).rrevert();
}
// Ensure enough output token has been sent to the taker.
if (outputTokenAmount < minOutputTokenAmount) {
LibTransformERC20RichErrors.IncompleteTransformERC20Error(
address(outputToken),
outputTokenAmount,
minOutputTokenAmount
).rrevert();
}
// Emit an event.
emit TransformedERC20(
taker,
address(inputToken),
address(outputToken),
inputTokenAmount,
outputTokenAmount
);
}
/// @dev Return the current wallet instance that will serve as the execution
/// context for transformations.
/// @return wallet The wallet instance.
function getTransformWallet()
public
override
view
returns (IFlashWallet wallet)
{
return LibTransformERC20Storage.getStorage().wallet;
}
/// @dev Transfer input tokens from the taker and any attached ETH to `to`
/// @param inputToken The token to pull from the taker.
/// @param from The from (taker) address.
/// @param to The recipient of tokens and ETH.
/// @param amount Amount of `inputToken` tokens to transfer.
function _transferInputTokensAndAttachedEth(
IERC20TokenV06 inputToken,
address from,
address payable to,
uint256 amount
)
private
{
// Transfer any attached ETH.
if (msg.value != 0) {
to.transfer(msg.value);
}
// Transfer input tokens.
if (!LibERC20Transformer.isTokenETH(inputToken)) {
// Token is not ETH, so pull ERC20 tokens.
ITokenSpender(address(this))._spendERC20Tokens(
inputToken,
from,
to,
amount
);
} else if (msg.value < amount) {
// Token is ETH, so the caller must attach enough ETH to the call.
LibTransformERC20RichErrors.InsufficientEthAttachedError(
msg.value,
amount
).rrevert();
}
}
/// @dev Executs a transformer in the context of `wallet`.
/// @param wallet The wallet instance.
/// @param transformation The transformation.
/// @param transformerDeployer The address of the transformer deployer.
/// @param taker The taker address.
/// @param callDataHash Hash of the calldata.
function _executeTransformation(
IFlashWallet wallet,
Transformation memory transformation,
address transformerDeployer,
address payable taker,
bytes32 callDataHash
)
private
{
// Derive the transformer address from the deployment nonce.
address payable transformer = LibERC20Transformer.getDeployedAddress(
transformerDeployer,
transformation.deploymentNonce
);
// Call `transformer.transform()` as the wallet.
bytes memory resultData = wallet.executeDelegateCall(
// The call target.
transformer,
// Call data.
abi.encodeWithSelector(
IERC20Transformer.transform.selector,
callDataHash,
taker,
transformation.data
)
);
// Ensure the transformer returned the magic bytes.
if (resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != LibERC20Transformer.TRANSFORMER_SUCCESS
) {
LibTransformERC20RichErrors.TransformerFailedError(
transformer,
transformation.data,
resultData
).rrevert();
}
}
}
/*
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 "./LibStorage.sol";
import "../external/IFlashWallet.sol";
/// @dev Storage helpers for the `TokenSpender` feature.
library LibTransformERC20Storage {
/// @dev Storage bucket for this feature.
struct Storage {
// The current wallet instance.
IFlashWallet wallet;
// The transformer deployer address.
address transformerDeployer;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.TransformERC20
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
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/LibERC20TokenV06.sol";
library LibERC20Transformer {
using LibERC20TokenV06 for IERC20TokenV06;
/// @dev ETH pseudo-token address.
address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Return value indicating success in `IERC20Transformer.transform()`.
/// This is just `keccak256('TRANSFORMER_SUCCESS')`.
bytes4 constant internal TRANSFORMER_SUCCESS = 0x13c9929e;
/// @dev Transfer ERC20 tokens and ETH.
/// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`).
/// @param to The recipient.
/// @param amount The transfer amount.
function transformerTransfer(
IERC20TokenV06 token,
address payable to,
uint256 amount
)
internal
{
if (isTokenETH(token)) {
to.transfer(amount);
} else {
token.compatTransfer(to, amount);
}
}
/// @dev Check if a token is the ETH pseudo-token.
/// @param token The token to check.
/// @return isETH `true` if the token is the ETH pseudo-token.
function isTokenETH(IERC20TokenV06 token)
internal
pure
returns (bool isETH)
{
return address(token) == ETH_TOKEN_ADDRESS;
}
/// @dev Check the balance of an ERC20 token or ETH.
/// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`).
/// @param owner Holder of the tokens.
/// @return tokenBalance The balance of `owner`.
function getTokenBalanceOf(IERC20TokenV06 token, address owner)
internal
view
returns (uint256 tokenBalance)
{
if (isTokenETH(token)) {
return owner.balance;
}
return token.balanceOf(owner);
}
/// @dev RLP-encode a 32-bit or less account nonce.
/// @param nonce A positive integer in the range 0 <= nonce < 2^32.
/// @return rlpNonce The RLP encoding.
function rlpEncodeNonce(uint32 nonce)
internal
pure
returns (bytes memory rlpNonce)
{
// See https://github.com/ethereum/wiki/wiki/RLP for RLP encoding rules.
if (nonce == 0) {
rlpNonce = new bytes(1);
rlpNonce[0] = 0x80;
} else if (nonce < 0x80) {
rlpNonce = new bytes(1);
rlpNonce[0] = byte(uint8(nonce));
} else if (nonce <= 0xFF) {
rlpNonce = new bytes(2);
rlpNonce[0] = 0x81;
rlpNonce[1] = byte(uint8(nonce));
} else if (nonce <= 0xFFFF) {
rlpNonce = new bytes(3);
rlpNonce[0] = 0x82;
rlpNonce[1] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[2] = byte(uint8(nonce));
} else if (nonce <= 0xFFFFFF) {
rlpNonce = new bytes(4);
rlpNonce[0] = 0x83;
rlpNonce[1] = byte(uint8((nonce & 0xFF0000) >> 16));
rlpNonce[2] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[3] = byte(uint8(nonce));
} else {
rlpNonce = new bytes(5);
rlpNonce[0] = 0x84;
rlpNonce[1] = byte(uint8((nonce & 0xFF000000) >> 24));
rlpNonce[2] = byte(uint8((nonce & 0xFF0000) >> 16));
rlpNonce[3] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[4] = byte(uint8(nonce));
}
}
/// @dev Compute the expected deployment address by `deployer` at
/// the nonce given by `deploymentNonce`.
/// @param deployer The address of the deployer.
/// @param deploymentNonce The nonce that the deployer had when deploying
/// a contract.
/// @return deploymentAddress The deployment address.
function getDeployedAddress(address deployer, uint32 deploymentNonce)
internal
pure
returns (address payable deploymentAddress)
{
// The address of if a deployed contract is the lower 20 bytes of the
// hash of the RLP-encoded deployer's account address + account nonce.
// See: https://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
bytes memory rlpNonce = rlpEncodeNonce(deploymentNonce);
return address(uint160(uint256(keccak256(abi.encodePacked(
byte(uint8(0xC0 + 21 + rlpNonce.length)),
byte(uint8(0x80 + 20)),
deployer,
rlpNonce
)))));
}
}
/*
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 "../ZeroEx.sol";
import "../features/IOwnable.sol";
import "../features/TokenSpender.sol";
import "../features/TransformERC20.sol";
import "../external/AllowanceTarget.sol";
import "./InitialMigration.sol";
/// @dev A contract for deploying and configuring the full ZeroEx contract.
contract FullMigration {
// solhint-disable no-empty-blocks,indent
/// @dev Features to add the the proxy contract.
struct Features {
SimpleFunctionRegistry registry;
Ownable ownable;
TokenSpender tokenSpender;
TransformERC20 transformERC20;
}
/// @dev Parameters needed to initialize features.
struct MigrateOpts {
address transformerDeployer;
}
/// @dev The allowed caller of `deploy()`.
address public immutable deployer;
/// @dev The initial migration contract.
InitialMigration private _initialMigration;
/// @dev Instantiate this contract and set the allowed caller of `deploy()`
/// to `deployer`.
/// @param deployer_ The allowed caller of `deploy()`.
constructor(address payable deployer_)
public
{
deployer = deployer_;
// Create an initial migration contract with this contract set to the
// allowed deployer.
_initialMigration = new InitialMigration(address(this));
}
/// @dev Deploy the `ZeroEx` contract with the full feature set,
/// transfer ownership to `owner`, then self-destruct.
/// @param owner The owner of the contract.
/// @param features Features to add to the proxy.
/// @return zeroEx The deployed and configured `ZeroEx` contract.
/// @param migrateOpts Parameters needed to initialize features.
function deploy(
address payable owner,
Features memory features,
MigrateOpts memory migrateOpts
)
public
returns (ZeroEx zeroEx)
{
require(msg.sender == deployer, "FullMigration/INVALID_SENDER");
// Perform the initial migration with the owner set to this contract.
zeroEx = _initialMigration.deploy(
address(uint160(address(this))),
InitialMigration.BootstrapFeatures({
registry: features.registry,
ownable: features.ownable
})
);
// Add features.
_addFeatures(zeroEx, owner, features, migrateOpts);
// Transfer ownership to the real owner.
IOwnable(address(zeroEx)).transferOwnership(owner);
// Self-destruct.
this.die(owner);
}
/// @dev Destroy this contract. Only callable from ourselves (from `deploy()`).
/// @param ethRecipient Receiver of any ETH in this contract.
function die(address payable ethRecipient)
external
virtual
{
require(msg.sender == address(this), "FullMigration/INVALID_SENDER");
// This contract should not hold any funds but we send
// them to the ethRecipient just in case.
selfdestruct(ethRecipient);
}
/// @dev Deploy and register features to the ZeroEx contract.
/// @param zeroEx The bootstrapped ZeroEx contract.
/// @param owner The ultimate owner of the ZeroEx contract.
/// @param features Features to add to the proxy.
/// @param migrateOpts Parameters needed to initialize features.
function _addFeatures(
ZeroEx zeroEx,
address owner,
Features memory features,
MigrateOpts memory migrateOpts
)
private
{
IOwnable ownable = IOwnable(address(zeroEx));
// TokenSpender
{
// Create the allowance target.
AllowanceTarget allowanceTarget = new AllowanceTarget();
// Let the ZeroEx contract use the allowance target.
allowanceTarget.addAuthorizedAddress(address(zeroEx));
// Transfer ownership of the allowance target to the (real) owner.
allowanceTarget.transferOwnership(owner);
// Register the feature.
ownable.migrate(
address(features.tokenSpender),
abi.encodeWithSelector(
TokenSpender.migrate.selector,
allowanceTarget
),
address(this)
);
}
// TransformERC20
{
// Register the feature.
ownable.migrate(
address(features.transformERC20),
abi.encodeWithSelector(
TransformERC20.migrate.selector,
migrateOpts.transformerDeployer
),
address(this)
);
}
}
}
/*
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 "../ZeroEx.sol";
import "../features/IBootstrap.sol";
import "../features/SimpleFunctionRegistry.sol";
import "../features/Ownable.sol";
import "./LibBootstrap.sol";
/// @dev A contract for deploying and configuring a minimal ZeroEx contract.
contract InitialMigration {
/// @dev Features to bootstrap into the the proxy contract.
struct BootstrapFeatures {
SimpleFunctionRegistry registry;
Ownable ownable;
}
/// @dev The allowed caller of `deploy()`. In production, this would be
/// the governor.
address public immutable deployer;
/// @dev The real address of this contract.
address private immutable _implementation;
/// @dev Instantiate this contract and set the allowed caller of `deploy()`
/// to `deployer_`.
/// @param deployer_ The allowed caller of `deploy()`.
constructor(address deployer_) public {
deployer = deployer_;
_implementation = address(this);
}
/// @dev Deploy the `ZeroEx` contract with the minimum feature set,
/// transfers ownership to `owner`, then self-destructs.
/// Only callable by `deployer` set in the contstructor.
/// @param owner The owner of the contract.
/// @param features Features to bootstrap into the proxy.
/// @return zeroEx The deployed and configured `ZeroEx` contract.
function deploy(address payable owner, BootstrapFeatures memory features)
public
virtual
returns (ZeroEx zeroEx)
{
// Must be called by the allowed deployer.
require(msg.sender == deployer, "InitialMigration/INVALID_SENDER");
// Deploy the ZeroEx contract, setting ourselves as the bootstrapper.
zeroEx = new ZeroEx();
// Bootstrap the initial feature set.
IBootstrap(address(zeroEx)).bootstrap(
address(this),
abi.encodeWithSelector(this.bootstrap.selector, owner, features)
);
// Self-destruct. This contract should not hold any funds but we send
// them to the owner just in case.
this.die(owner);
}
/// @dev Sets up the initial state of the `ZeroEx` contract.
/// The `ZeroEx` contract will delegatecall into this function.
/// @param owner The new owner of the ZeroEx contract.
/// @param features Features to bootstrap into the proxy.
/// @return success Magic bytes if successful.
function bootstrap(address owner, BootstrapFeatures memory features)
public
virtual
returns (bytes4 success)
{
// Deploy and migrate the initial features.
// Order matters here.
// Initialize Registry.
LibBootstrap.delegatecallBootstrapFunction(
address(features.registry),
abi.encodeWithSelector(
SimpleFunctionRegistry.bootstrap.selector
)
);
// Initialize Ownable.
LibBootstrap.delegatecallBootstrapFunction(
address(features.ownable),
abi.encodeWithSelector(
Ownable.bootstrap.selector
)
);
// De-register `SimpleFunctionRegistry._extendSelf`.
SimpleFunctionRegistry(address(this)).rollback(
SimpleFunctionRegistry._extendSelf.selector,
address(0)
);
// Transfer ownership to the real owner.
Ownable(address(this)).transferOwnership(owner);
success = LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Self-destructs this contract. Only callable by this contract.
/// @param ethRecipient Who to transfer outstanding ETH to.
function die(address payable ethRecipient) public virtual {
require(msg.sender == _implementation, "InitialMigration/INVALID_SENDER");
selfdestruct(ethRecipient);
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that transfers tokens to arbitrary addresses.
contract AffiliateFeeTransformer is
Transformer
{
// solhint-disable no-empty-blocks
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Information for a single fee.
struct TokenFee {
// The token to transfer to `recipient`.
IERC20TokenV06 token;
// Amount of each `token` to transfer to `recipient`.
// If `amount == uint256(-1)`, the entire balance of `token` will be
// transferred.
uint256 amount;
// Recipient of `token`.
address payable recipient;
}
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Create this contract.
constructor()
public
Transformer()
{}
/// @dev Transfers tokens to recipients.
/// @param data ABI-encoded `TokenFee[]`, indicating which tokens to transfer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data
)
external
override
returns (bytes4 success)
{
TokenFee[] memory fees = abi.decode(data, (TokenFee[]));
// Transfer tokens to recipients.
for (uint256 i = 0; i < fees.length; ++i) {
uint256 amount = fees[i].amount;
if (amount == MAX_UINT256) {
amount = LibERC20Transformer.getTokenBalanceOf(fees[i].token, address(this));
}
if (amount != 0) {
fees[i].token.transformerTransfer(fees[i].recipient, amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./IERC20Transformer.sol";
/// @dev Abstract base class for transformers.
abstract contract Transformer is
IERC20Transformer
{
using LibRichErrorsV06 for bytes;
/// @dev The address of the deployer.
address public immutable deployer;
/// @dev The original address of this contract.
address private immutable _implementation;
/// @dev Create this contract.
constructor() public {
deployer = msg.sender;
_implementation = address(this);
}
/// @dev Destruct this contract. Only callable by the deployer and will not
/// succeed in the context of a delegatecall (from another contract).
/// @param ethRecipient The recipient of ETH held in this contract.
function die(address payable ethRecipient)
external
virtual
{
// Only the deployer can call this.
if (msg.sender != deployer) {
LibTransformERC20RichErrors
.OnlyCallableByDeployerError(msg.sender, deployer)
.rrevert();
}
// Must be executing our own context.
if (address(this) != _implementation) {
LibTransformERC20RichErrors
.InvalidExecutionContextError(address(this), _implementation)
.rrevert();
}
selfdestruct(ethRecipient);
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "../vendor/v3/IExchange.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that fills an ERC20 market sell/buy quote.
contract FillQuoteTransformer is
Transformer
{
using LibERC20TokenV06 for IERC20TokenV06;
using LibERC20Transformer for IERC20TokenV06;
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
/// @dev Whether we are performing a market sell or buy.
enum Side {
Sell,
Buy
}
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// Whether we aer performing a market sell or buy.
Side side;
// The token being sold.
// This should be an actual token, not the ETH pseudo-token.
IERC20TokenV06 sellToken;
// The token being bought.
// This should be an actual token, not the ETH pseudo-token.
IERC20TokenV06 buyToken;
// The orders to fill.
IExchange.Order[] orders;
// Signatures for each respective order in `orders`.
bytes[] signatures;
// Maximum fill amount for each order. This may be shorter than the
// number of orders, where missing entries will be treated as `uint256(-1)`.
// For sells, this will be the maximum sell amount (taker asset).
// For buys, this will be the maximum buy amount (maker asset).
uint256[] maxOrderFillAmounts;
// Amount of `sellToken` to sell or `buyToken` to buy.
// For sells, this may be `uint256(-1)` to sell the entire balance of
// `sellToken`.
uint256 fillAmount;
}
/// @dev Results of a call to `_fillOrder()`.
struct FillOrderResults {
// The amount of taker tokens sold, according to balance checks.
uint256 takerTokenSoldAmount;
// The amount of maker tokens sold, according to balance checks.
uint256 makerTokenBoughtAmount;
// The amount of protocol fee paid.
uint256 protocolFeePaid;
}
/// @dev The Exchange ERC20Proxy ID.
bytes4 private constant ERC20_ASSET_PROXY_ID = 0xf47261b0;
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev The Exchange contract.
IExchange public immutable exchange;
/// @dev The ERC20Proxy address.
address public immutable erc20Proxy;
/// @dev Create this contract.
/// @param exchange_ The Exchange V3 instance.
constructor(IExchange exchange_)
public
Transformer()
{
exchange = exchange_;
erc20Proxy = exchange_.getAssetProxy(ERC20_ASSET_PROXY_ID);
}
/// @dev Sell this contract's entire balance of of `sellToken` in exchange
/// for `buyToken` by filling `orders`. Protocol fees should be attached
/// to this call. `buyToken` and excess ETH will be transferred back to the caller.
/// @param data_ ABI-encoded `TransformData`.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
// Validate data fields.
if (data.sellToken.isTokenETH() || data.buyToken.isTokenETH()) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
data_
).rrevert();
}
if (data.orders.length != data.signatures.length) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH,
data_
).rrevert();
}
if (data.side == Side.Sell && data.fillAmount == MAX_UINT256) {
// If `sellAmount == -1 then we are selling
// the entire balance of `sellToken`. This is useful in cases where
// the exact sell amount is not exactly known in advance, like when
// unwrapping Chai/cUSDC/cDAI.
data.fillAmount = data.sellToken.getTokenBalanceOf(address(this));
}
// Approve the ERC20 proxy to spend `sellToken`.
data.sellToken.approveIfBelow(erc20Proxy, data.fillAmount);
// Fill the orders.
uint256 singleProtocolFee = exchange.protocolFeeMultiplier().safeMul(tx.gasprice);
uint256 ethRemaining = address(this).balance;
uint256 boughtAmount = 0;
uint256 soldAmount = 0;
for (uint256 i = 0; i < data.orders.length; ++i) {
// Check if we've hit our targets.
if (data.side == Side.Sell) {
// Market sell check.
if (soldAmount >= data.fillAmount) {
break;
}
} else {
// Market buy check.
if (boughtAmount >= data.fillAmount) {
break;
}
}
// Ensure we have enough ETH to cover the protocol fee.
if (ethRemaining < singleProtocolFee) {
LibTransformERC20RichErrors
.InsufficientProtocolFeeError(ethRemaining, singleProtocolFee)
.rrevert();
}
// Fill the order.
FillOrderResults memory results;
if (data.side == Side.Sell) {
// Market sell.
results = _sellToOrder(
data.buyToken,
data.sellToken,
data.orders[i],
data.signatures[i],
data.fillAmount.safeSub(soldAmount).min256(
data.maxOrderFillAmounts.length > i
? data.maxOrderFillAmounts[i]
: MAX_UINT256
),
singleProtocolFee
);
} else {
// Market buy.
results = _buyFromOrder(
data.buyToken,
data.sellToken,
data.orders[i],
data.signatures[i],
data.fillAmount.safeSub(boughtAmount).min256(
data.maxOrderFillAmounts.length > i
? data.maxOrderFillAmounts[i]
: MAX_UINT256
),
singleProtocolFee
);
}
// Accumulate totals.
soldAmount = soldAmount.safeAdd(results.takerTokenSoldAmount);
boughtAmount = boughtAmount.safeAdd(results.makerTokenBoughtAmount);
ethRemaining = ethRemaining.safeSub(results.protocolFeePaid);
}
// Ensure we hit our targets.
if (data.side == Side.Sell) {
// Market sell check.
if (soldAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillSellQuoteError(
address(data.sellToken),
soldAmount,
data.fillAmount
).rrevert();
}
} else {
// Market buy check.
if (boughtAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillBuyQuoteError(
address(data.buyToken),
boughtAmount,
data.fillAmount
).rrevert();
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
/// @dev Try to sell up to `sellAmount` from an order.
/// @param makerToken The maker/buy token.
/// @param takerToken The taker/sell token.
/// @param order The order to fill.
/// @param signature The signature for `order`.
/// @param sellAmount Amount of taker token to sell.
/// @param protocolFee The protocol fee needed to fill `order`.
function _sellToOrder(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
IExchange.Order memory order,
bytes memory signature,
uint256 sellAmount,
uint256 protocolFee
)
private
returns (FillOrderResults memory results)
{
IERC20TokenV06 takerFeeToken =
_getTokenFromERC20AssetData(order.takerFeeAssetData);
uint256 takerTokenFillAmount = sellAmount;
if (order.takerFee != 0) {
if (takerFeeToken == makerToken) {
// Taker fee is payable in the maker token, so we need to
// approve the proxy to spend the maker token.
// It isn't worth computing the actual taker fee
// since `approveIfBelow()` will set the allowance to infinite. We
// just need a reasonable upper bound to avoid unnecessarily re-approving.
takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee);
} else if (takerFeeToken == takerToken){
// Taker fee is payable in the taker token, so we need to
// reduce the fill amount to cover the fee.
// takerTokenFillAmount' =
// (takerTokenFillAmount * order.takerAssetAmount) /
// (order.takerAssetAmount + order.takerFee)
takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
order.takerAssetAmount,
order.takerAssetAmount.safeAdd(order.takerFee),
sellAmount
);
} else {
// Only support taker or maker asset denominated taker fees.
LibTransformERC20RichErrors.InvalidTakerFeeTokenError(
address(takerFeeToken)
).rrevert();
}
}
// Clamp fill amount to order size.
takerTokenFillAmount = LibSafeMathV06.min256(
takerTokenFillAmount,
order.takerAssetAmount
);
// Perform the fill.
return _fillOrder(
order,
signature,
takerTokenFillAmount,
protocolFee,
makerToken,
takerFeeToken == takerToken
);
}
/// @dev Try to buy up to `buyAmount` from an order.
/// @param makerToken The maker/buy token.
/// @param takerToken The taker/sell token.
/// @param order The order to fill.
/// @param signature The signature for `order`.
/// @param buyAmount Amount of maker token to buy.
/// @param protocolFee The protocol fee needed to fill `order`.
function _buyFromOrder(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
IExchange.Order memory order,
bytes memory signature,
uint256 buyAmount,
uint256 protocolFee
)
private
returns (FillOrderResults memory results)
{
IERC20TokenV06 takerFeeToken =
_getTokenFromERC20AssetData(order.takerFeeAssetData);
// Compute the default taker token fill amount.
uint256 takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
buyAmount,
order.makerAssetAmount,
order.takerAssetAmount
);
if (order.takerFee != 0) {
if (takerFeeToken == makerToken) {
// Taker fee is payable in the maker token.
// Adjust the taker token fill amount to account for maker
// tokens being lost to the taker fee.
// takerTokenFillAmount' =
// (order.takerAssetAmount * buyAmount) /
// (order.makerAssetAmount - order.takerFee)
takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
buyAmount,
order.makerAssetAmount.safeSub(order.takerFee),
order.takerAssetAmount
);
// Approve the proxy to spend the maker token.
// It isn't worth computing the actual taker fee
// since `approveIfBelow()` will set the allowance to infinite. We
// just need a reasonable upper bound to avoid unnecessarily re-approving.
takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee);
} else if (takerFeeToken != takerToken) {
// Only support taker or maker asset denominated taker fees.
LibTransformERC20RichErrors.InvalidTakerFeeTokenError(
address(takerFeeToken)
).rrevert();
}
}
// Clamp to order size.
takerTokenFillAmount = LibSafeMathV06.min256(
order.takerAssetAmount,
takerTokenFillAmount
);
// Perform the fill.
return _fillOrder(
order,
signature,
takerTokenFillAmount,
protocolFee,
makerToken,
takerFeeToken == takerToken
);
}
/// @dev Attempt to fill an order. If the fill reverts, the revert will be
/// swallowed and `results` will be zeroed out.
/// @param order The order to fill.
/// @param signature The order signature.
/// @param takerAssetFillAmount How much taker asset to fill.
/// @param protocolFee The protocol fee needed to fill this order.
/// @param makerToken The maker token.
/// @param isTakerFeeInTakerToken Whether the taker fee token is the same as the
/// taker token.
function _fillOrder(
IExchange.Order memory order,
bytes memory signature,
uint256 takerAssetFillAmount,
uint256 protocolFee,
IERC20TokenV06 makerToken,
bool isTakerFeeInTakerToken
)
private
returns (FillOrderResults memory results)
{
// Track changes in the maker token balance.
uint256 initialMakerTokenBalance = makerToken.balanceOf(address(this));
try
exchange.fillOrder
{value: protocolFee}
(order, takerAssetFillAmount, signature)
returns (IExchange.FillResults memory fillResults)
{
// Update maker quantity based on changes in token balances.
results.makerTokenBoughtAmount = makerToken.balanceOf(address(this))
.safeSub(initialMakerTokenBalance);
// We can trust the other fill result quantities.
results.protocolFeePaid = fillResults.protocolFeePaid;
results.takerTokenSoldAmount = fillResults.takerAssetFilledAmount;
// If the taker fee is payable in the taker asset, include the
// taker fee in the total amount sold.
if (isTakerFeeInTakerToken) {
results.takerTokenSoldAmount =
results.takerTokenSoldAmount.safeAdd(fillResults.takerFeePaid);
}
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
}
}
/// @dev Extract the token from plain ERC20 asset data.
/// If the asset-data is empty, a zero token address will be returned.
/// @param assetData The order asset data.
function _getTokenFromERC20AssetData(bytes memory assetData)
private
pure
returns (IERC20TokenV06 token)
{
if (assetData.length == 0) {
return IERC20TokenV06(address(0));
}
if (assetData.length != 36 ||
LibBytesV06.readBytes4(assetData, 0) != ERC20_ASSET_PROXY_ID)
{
LibTransformERC20RichErrors
.InvalidERC20AssetDataError(assetData)
.rrevert();
}
return IERC20TokenV06(LibBytesV06.readAddress(assetData, 16));
}
}
/*
Copyright 2019 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;
import "./LibSafeMathV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibMathRichErrorsV06.sol";
library LibMathV06 {
using LibSafeMathV06 for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
/*
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;
library LibMathRichErrorsV06 {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
/*
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;
/// @dev Interface to the V3 Exchange.
interface IExchange {
/// @dev V3 Order structure.
struct Order {
// Address that created the order.
address makerAddress;
// Address that is allowed to fill the order.
// If set to 0, any address is allowed to fill the order.
address takerAddress;
// Address that will recieve fees when order is filled.
address feeRecipientAddress;
// Address that is allowed to call Exchange contract methods that affect this order.
// If set to 0, any address is allowed to call these methods.
address senderAddress;
// Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 makerAssetAmount;
// Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 takerAssetAmount;
// Fee paid to feeRecipient by maker when order is filled.
uint256 makerFee;
// Fee paid to feeRecipient by taker when order is filled.
uint256 takerFee;
// Timestamp in seconds at which order expires.
uint256 expirationTimeSeconds;
// Arbitrary number to facilitate uniqueness of the order's hash.
uint256 salt;
// Encoded data that can be decoded by a specified proxy contract when transferring makerAsset.
// The leading bytes4 references the id of the asset proxy.
bytes makerAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring takerAsset.
// The leading bytes4 references the id of the asset proxy.
bytes takerAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset.
// The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset.
// The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData;
}
/// @dev V3 `fillOrder()` results.`
struct FillResults {
// Total amount of makerAsset(s) filled.
uint256 makerAssetFilledAmount;
// Total amount of takerAsset(s) filled.
uint256 takerAssetFilledAmount;
// Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 makerFeePaid;
// Total amount of fees paid by taker to feeRecipients(s).
uint256 takerFeePaid;
// Total amount of fees paid by taker to the staking contract.
uint256 protocolFeePaid;
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function fillOrder(
Order calldata order,
uint256 takerAssetFillAmount,
bytes calldata signature
)
external
payable
returns (FillResults memory fillResults);
/// @dev Returns the protocolFeeMultiplier
/// @return multiplier The multiplier for protocol fees.
function protocolFeeMultiplier()
external
view
returns (uint256 multiplier);
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return proxyAddress The asset proxy registered to assetProxyId.
/// Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address proxyAddress);
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that transfers tokens to the taker.
contract PayTakerTransformer is
Transformer
{
// solhint-disable no-empty-blocks
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// The tokens to transfer to the taker.
IERC20TokenV06[] tokens;
// Amount of each token in `tokens` to transfer to the taker.
// `uint(-1)` will transfer the entire balance.
uint256[] amounts;
}
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Create this contract.
constructor()
public
Transformer()
{}
/// @dev Forwards tokens to the taker.
/// @param taker The taker address (caller of `TransformERC20.transformERC20()`).
/// @param data_ ABI-encoded `TransformData`, indicating which tokens to transfer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
// Transfer tokens directly to the taker.
for (uint256 i = 0; i < data.tokens.length; ++i) {
// The `amounts` array can be shorter than the `tokens` array.
// Missing elements are treated as `uint256(-1)`.
uint256 amount = data.amounts.length > i ? data.amounts[i] : uint256(-1);
if (amount == MAX_UINT256) {
amount = data.tokens[i].getTokenBalanceOf(address(this));
}
if (amount != 0) {
data.tokens[i].transformerTransfer(taker, amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that wraps or unwraps WETH.
contract WethTransformer is
Transformer
{
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// The token to wrap/unwrap. Must be either ETH or WETH.
IERC20TokenV06 token;
// Amount of `token` to wrap or unwrap.
// `uint(-1)` will unwrap the entire balance.
uint256 amount;
}
/// @dev The WETH contract address.
IEtherTokenV06 public immutable weth;
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Construct the transformer and store the WETH address in an immutable.
/// @param weth_ The weth token.
constructor(IEtherTokenV06 weth_)
public
Transformer()
{
weth = weth_;
}
/// @dev Wraps and unwraps WETH.
/// @param data_ ABI-encoded `TransformData`, indicating which token to wrap/umwrap.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
if (!data.token.isTokenETH() && data.token != weth) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
data_
).rrevert();
}
uint256 amount = data.amount;
if (amount == MAX_UINT256) {
amount = data.token.getTokenBalanceOf(address(this));
}
if (amount != 0) {
if (data.token.isTokenETH()) {
// Wrap ETH.
weth.deposit{value: amount}();
} else {
// Unwrap WETH.
weth.withdraw(amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
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;
import "./IERC20TokenV06.sol";
interface IEtherTokenV06 is
IERC20TokenV06
{
/// @dev Wrap ether.
function deposit() external payable;
/// @dev Unwrap ether.
function withdraw(uint256 amount) external;
}
/*
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;
interface ITestSimpleFunctionRegistryFeature {
function testFn() external view returns (uint256 id);
}
/*
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;
contract TestCallTarget {
event CallTargetCalled(
address context,
address sender,
bytes data,
uint256 value
);
bytes4 private constant MAGIC_BYTES = 0x12345678;
bytes private constant REVERTING_DATA = hex"1337";
fallback() external payable {
if (keccak256(msg.data) == keccak256(REVERTING_DATA)) {
revert("TestCallTarget/REVERT");
}
emit CallTargetCalled(
address(this),
msg.sender,
msg.data,
msg.value
);
bytes4 rval = MAGIC_BYTES;
assembly {
mstore(0, rval)
return(0, 32)
}
}
}
/*
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;
contract TestDelegateCaller {
function executeDelegateCall(
address target,
bytes calldata callData
)
external
{
(bool success, bytes memory resultData) = target.delegatecall(callData);
if (!success) {
assembly { revert(add(resultData, 32), mload(resultData)) }
}
assembly { return(add(resultData, 32), mload(resultData)) }
}
}
/*
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-utils/contracts/src/v06/LibBytesV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../src/vendor/v3/IExchange.sol";
import "./TestMintableERC20Token.sol";
contract TestFillQuoteTransformerExchange {
struct FillBehavior {
// How much of the order is filled, in taker asset amount.
uint256 filledTakerAssetAmount;
// Scaling for maker assets minted, in 1e18.
uint256 makerAssetMintRatio;
}
uint256 private constant PROTOCOL_FEE_MULTIPLIER = 1337;
using LibSafeMathV06 for uint256;
function fillOrder(
IExchange.Order calldata order,
uint256 takerAssetFillAmount,
bytes calldata signature
)
external
payable
returns (IExchange.FillResults memory fillResults)
{
require(
signature.length != 0,
"TestFillQuoteTransformerExchange/INVALID_SIGNATURE"
);
// The signature is the ABI-encoded FillBehavior data.
FillBehavior memory behavior = abi.decode(signature, (FillBehavior));
uint256 protocolFee = PROTOCOL_FEE_MULTIPLIER * tx.gasprice;
require(
msg.value == protocolFee,
"TestFillQuoteTransformerExchange/INSUFFICIENT_PROTOCOL_FEE"
);
// Return excess protocol fee.
msg.sender.transfer(msg.value - protocolFee);
// Take taker tokens.
TestMintableERC20Token takerToken = _getTokenFromAssetData(order.takerAssetData);
takerAssetFillAmount = LibSafeMathV06.min256(
order.takerAssetAmount.safeSub(behavior.filledTakerAssetAmount),
takerAssetFillAmount
);
require(
takerToken.getSpendableAmount(msg.sender, address(this)) >= takerAssetFillAmount,
"TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FUNDS"
);
takerToken.transferFrom(msg.sender, order.makerAddress, takerAssetFillAmount);
// Mint maker tokens.
uint256 makerAssetFilledAmount = LibMathV06.getPartialAmountFloor(
takerAssetFillAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
TestMintableERC20Token makerToken = _getTokenFromAssetData(order.makerAssetData);
makerToken.mint(
msg.sender,
LibMathV06.getPartialAmountFloor(
behavior.makerAssetMintRatio,
1e18,
makerAssetFilledAmount
)
);
// Take taker fee.
TestMintableERC20Token takerFeeToken = _getTokenFromAssetData(order.takerFeeAssetData);
uint256 takerFee = LibMathV06.getPartialAmountFloor(
takerAssetFillAmount,
order.takerAssetAmount,
order.takerFee
);
require(
takerFeeToken.getSpendableAmount(msg.sender, address(this)) >= takerFee,
"TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FEE_FUNDS"
);
takerFeeToken.transferFrom(msg.sender, order.feeRecipientAddress, takerFee);
fillResults.makerAssetFilledAmount = makerAssetFilledAmount;
fillResults.takerAssetFilledAmount = takerAssetFillAmount;
fillResults.makerFeePaid = uint256(-1);
fillResults.takerFeePaid = takerFee;
fillResults.protocolFeePaid = protocolFee;
}
function encodeBehaviorData(FillBehavior calldata behavior)
external
pure
returns (bytes memory encoded)
{
return abi.encode(behavior);
}
function protocolFeeMultiplier()
external
pure
returns (uint256)
{
return PROTOCOL_FEE_MULTIPLIER;
}
function getAssetProxy(bytes4)
external
view
returns (address)
{
return address(this);
}
function _getTokenFromAssetData(bytes memory assetData)
private
pure
returns (TestMintableERC20Token token)
{
return TestMintableERC20Token(LibBytesV06.readAddress(assetData, 16));
}
}
/*
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;
contract TestMintableERC20Token {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function transfer(address to, uint256 amount)
external
virtual
returns (bool)
{
return transferFrom(msg.sender, to, amount);
}
function approve(address spender, uint256 amount)
external
virtual
returns (bool)
{
allowance[msg.sender][spender] = amount;
return true;
}
function mint(address owner, uint256 amount)
external
virtual
{
balanceOf[owner] += amount;
}
function burn(address owner, uint256 amount)
external
virtual
{
require(balanceOf[owner] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS");
balanceOf[owner] -= amount;
}
function transferFrom(address from, address to, uint256 amount)
public
virtual
returns (bool)
{
if (from != msg.sender) {
require(
allowance[from][msg.sender] >= amount,
"TestMintableERC20Token/INSUFFICIENT_ALLOWANCE"
);
allowance[from][msg.sender] -= amount;
}
require(balanceOf[from] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS");
balanceOf[from] -= amount;
balanceOf[to] += amount;
return true;
}
function getSpendableAmount(address owner, address spender)
external
view
returns (uint256)
{
return balanceOf[owner] < allowance[owner][spender]
? balanceOf[owner]
: allowance[owner][spender];
}
}
/*
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 "../src/transformers/IERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
import "./TestTransformerHost.sol";
contract TestFillQuoteTransformerHost is
TestTransformerHost
{
function executeTransform(
IERC20Transformer transformer,
TestMintableERC20Token inputToken,
uint256 inputTokenAmount,
bytes calldata data
)
external
payable
{
if (inputTokenAmount != 0) {
inputToken.mint(address(this), inputTokenAmount);
}
// Have to make this call externally because transformers aren't payable.
this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data);
}
}
/*
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-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../src/transformers/IERC20Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerHost {
using LibERC20Transformer for IERC20TokenV06;
using LibRichErrorsV06 for bytes;
function rawExecuteTransform(
IERC20Transformer transformer,
bytes32 callDataHash,
address taker,
bytes calldata data
)
external
{
(bool _success, bytes memory resultData) =
address(transformer).delegatecall(abi.encodeWithSelector(
transformer.transform.selector,
callDataHash,
taker,
data
));
if (!_success) {
resultData.rrevert();
}
require(
abi.decode(resultData, (bytes4)) == LibERC20Transformer.TRANSFORMER_SUCCESS,
"TestTransformerHost/INVALID_TRANSFORMER_RESULT"
);
}
// solhint-disable
receive() external payable {}
// solhint-enable
}
/*
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 "../src/ZeroEx.sol";
import "../src/features/IBootstrap.sol";
import "../src/migrations/FullMigration.sol";
contract TestFullMigration is
FullMigration
{
address public dieRecipient;
// solhint-disable-next-line no-empty-blocks
constructor(address payable deployer) public FullMigration(deployer) {}
function die(address payable ethRecipient) external override {
dieRecipient = ethRecipient;
}
}
/*
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 "../src/ZeroEx.sol";
import "../src/features/IBootstrap.sol";
import "../src/migrations/InitialMigration.sol";
contract TestInitialMigration is
InitialMigration
{
address public bootstrapFeature;
address public dieRecipient;
// solhint-disable-next-line no-empty-blocks
constructor(address deployer) public InitialMigration(deployer) {}
function callBootstrap(ZeroEx zeroEx) external {
IBootstrap(address(zeroEx)).bootstrap(address(this), new bytes(0));
}
function bootstrap(address owner, BootstrapFeatures memory features)
public
override
returns (bytes4 success)
{
success = InitialMigration.bootstrap(owner, features);
// Snoop the bootstrap feature contract.
bootstrapFeature = ZeroEx(address(uint160(address(this))))
.getFunctionImplementation(IBootstrap.bootstrap.selector);
}
function die(address payable ethRecipient) public override {
dieRecipient = ethRecipient;
}
}
/*
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 "../src/migrations/LibMigrate.sol";
import "../src/features/IOwnable.sol";
contract TestMigrator {
event TestMigrateCalled(
bytes callData,
address owner
);
function succeedingMigrate() external returns (bytes4 success) {
emit TestMigrateCalled(
msg.data,
IOwnable(address(this)).owner()
);
return LibMigrate.MIGRATE_SUCCESS;
}
function failingMigrate() external returns (bytes4 success) {
emit TestMigrateCalled(
msg.data,
IOwnable(address(this)).owner()
);
return 0xdeadbeef;
}
function revertingMigrate() external pure {
revert("OOPSIE");
}
}
/*
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 "../src/transformers/IERC20Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
contract TestMintTokenERC20Transformer is
IERC20Transformer
{
struct TransformData {
IERC20TokenV06 inputToken;
TestMintableERC20Token outputToken;
uint256 burnAmount;
uint256 mintAmount;
uint256 feeAmount;
}
event MintTransform(
address context,
address caller,
bytes32 callDataHash,
address taker,
bytes data,
uint256 inputTokenBalance,
uint256 ethBalance
);
function transform(
bytes32 callDataHash,
address payable taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
emit MintTransform(
address(this),
msg.sender,
callDataHash,
taker,
data_,
data.inputToken.balanceOf(address(this)),
address(this).balance
);
// "Burn" input tokens.
data.inputToken.transfer(address(0), data.burnAmount);
// Mint output tokens.
if (LibERC20Transformer.isTokenETH(IERC20TokenV06(address(data.outputToken)))) {
taker.transfer(data.mintAmount);
} else {
data.outputToken.mint(
taker,
data.mintAmount
);
// Burn fees from output.
data.outputToken.burn(taker, data.feeAmount);
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
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 "../src/fixins/FixinCommon.sol";
contract TestSimpleFunctionRegistryFeatureImpl1 is
FixinCommon
{
function testFn()
external
pure
returns (uint256 id)
{
return 1337;
}
}
/*
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 "../src/fixins/FixinCommon.sol";
contract TestSimpleFunctionRegistryFeatureImpl2 is
FixinCommon
{
function testFn()
external
pure
returns (uint256 id)
{
return 1338;
}
}
/*
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 "../src/features/TokenSpender.sol";
contract TestTokenSpender is
TokenSpender
{
modifier onlySelf() override {
_;
}
}
/*
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 "./TestMintableERC20Token.sol";
contract TestTokenSpenderERC20Token is
TestMintableERC20Token
{
event TransferFromCalled(
address sender,
address from,
address to,
uint256 amount
);
// `transferFrom()` behavior depends on the value of `amount`.
uint256 constant private EMPTY_RETURN_AMOUNT = 1337;
uint256 constant private FALSE_RETURN_AMOUNT = 1338;
uint256 constant private REVERT_RETURN_AMOUNT = 1339;
function transferFrom(address from, address to, uint256 amount)
public
override
returns (bool)
{
emit TransferFromCalled(msg.sender, from, to, amount);
if (amount == EMPTY_RETURN_AMOUNT) {
assembly { return(0, 0) }
}
if (amount == FALSE_RETURN_AMOUNT) {
return false;
}
if (amount == REVERT_RETURN_AMOUNT) {
revert("TestTokenSpenderERC20Token/Revert");
}
return true;
}
function setBalanceAndAllowanceOf(
address owner,
uint256 balance,
address spender,
uint256 allowance_
)
external
{
balanceOf[owner] = balance;
allowance[owner][spender] = allowance_;
}
}
/*
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 "../src/features/TransformERC20.sol";
contract TestTransformERC20 is
TransformERC20
{
// solhint-disable no-empty-blocks
constructor()
TransformERC20()
public
{}
modifier onlySelf() override {
_;
}
}
/*
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 "../src/transformers/Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerBase is
Transformer
{
function transform(
bytes32,
address payable,
bytes calldata
)
external
override
returns (bytes4 success)
{
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
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 "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerDeployerTransformer {
address payable public immutable deployer;
constructor() public payable {
deployer = msg.sender;
}
modifier onlyDeployer() {
require(msg.sender == deployer, "TestTransformerDeployerTransformer/ONLY_DEPLOYER");
_;
}
function die()
external
onlyDeployer
{
selfdestruct(deployer);
}
function isDeployedByDeployer(uint32 nonce)
external
view
returns (bool)
{
return LibERC20Transformer.getDeployedAddress(deployer, nonce) == address(this);
}
}
/*
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 "./TestMintableERC20Token.sol";
contract TestWeth is
TestMintableERC20Token
{
function deposit()
external
payable
{
this.mint(msg.sender, msg.value);
}
function withdraw(uint256 amount)
external
{
require(balanceOf[msg.sender] >= amount, "TestWeth/INSUFFICIENT_FUNDS");
balanceOf[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
/*
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 "../src/transformers/IERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
import "./TestTransformerHost.sol";
import "./TestWeth.sol";
contract TestWethTransformerHost is
TestTransformerHost
{
// solhint-disable
TestWeth private immutable _weth;
// solhint-enable
constructor(TestWeth weth) public {
_weth = weth;
}
function executeTransform(
uint256 wethAmount,
IERC20Transformer transformer,
bytes calldata data
)
external
payable
{
if (wethAmount != 0) {
_weth.deposit{value: wethAmount}();
}
// Have to make this call externally because transformers aren't payable.
this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data);
}
}
/*
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 "../src/fixins/FixinCommon.sol";
import "../src/ZeroEx.sol";
contract TestZeroExFeature is
FixinCommon
{
event PayableFnCalled(uint256 value);
event NotPayableFnCalled();
function payableFn()
external
payable
{
emit PayableFnCalled(msg.value);
}
function notPayableFn()
external
{
emit NotPayableFnCalled();
}
// solhint-disable no-empty-blocks
function unimplmentedFn()
external
{}
function internalFn()
external
onlySelf
{}
}
| Transfers ERC20 tokens from `owner` to `to`. Only callable from within. token The token to spend. owner The owner of the tokens. to The recipient of the tokens. amount The amount of `token` to transfer. Have the allowance target execute an ERC20 `transferFrom()`. | function _spendERC20Tokens(
IERC20TokenV06 token,
address owner,
address to,
uint256 amount
)
external
override
onlySelf
{
IAllowanceTarget spender = LibTokenSpenderStorage.getStorage().allowanceTarget;
(bool didSucceed, bytes memory resultData) = address(spender).call(
abi.encodeWithSelector(
IAllowanceTarget.executeCall.selector,
address(token),
abi.encodeWithSelector(
IERC20TokenV06.transferFrom.selector,
owner,
to,
amount
)
)
);
if (didSucceed) {
resultData = abi.decode(resultData, (bytes));
}
if (!didSucceed || !LibERC20TokenV06.isSuccessfulResult(resultData)) {
LibSpenderRichErrors.SpenderERC20TransferFromFailedError(
address(token),
owner,
to,
amount,
resultData
).rrevert();
}
}
| 5,368,709 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = 0x0;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract PresaleOracles is Claimable {
/*
* PresaleOracles
* Simple Presale contract
* built by github.com/rstormsf Roman Storm
*/
using SafeMath for uint256;
uint256 public startTime;
uint256 public endTime;
uint256 public cap;
uint256 public totalInvestedInWei;
uint256 public minimumContribution;
mapping(address => uint256) public investorBalances;
mapping(address => bool) public whitelist;
uint256 public investorsLength;
address public vault;
bool public isInitialized = false;
// TESTED by Roman Storm
function () public payable {
buy();
}
//TESTED by Roman Storm
function Presale() public {
}
//TESTED by Roman Storm
function initialize(uint256 _startTime, uint256 _endTime, uint256 _cap, uint256 _minimumContribution, address _vault) public onlyOwner {
require(!isInitialized);
require(_startTime != 0);
require(_endTime != 0);
require(_endTime > _startTime);
require(_cap != 0);
require(_minimumContribution != 0);
require(_vault != 0x0);
require(_cap > _minimumContribution);
startTime = _startTime;
endTime = _endTime;
cap = _cap;
isInitialized = true;
minimumContribution = _minimumContribution;
vault = _vault;
}
//TESTED by Roman Storm
event Contribution(address indexed investor, uint256 investorAmount, uint256 investorTotal, uint256 totalAmount);
function buy() public payable {
require(whitelist[msg.sender]);
require(isValidPurchase(msg.value));
require(isInitialized);
require(getTime() >= startTime && getTime() <= endTime);
address investor = msg.sender;
investorBalances[investor] += msg.value;
totalInvestedInWei += msg.value;
forwardFunds(msg.value);
Contribution(msg.sender, msg.value, investorBalances[investor], totalInvestedInWei);
}
//TESTED by Roman Storm
function forwardFunds(uint256 _amount) internal {
vault.transfer(_amount);
}
//TESTED by Roman Storm
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
function getTime() internal view returns(uint256) {
return now;
}
//TESTED by Roman Storm
function isValidPurchase(uint256 _amount) public view returns(bool) {
bool nonZero = _amount > 0;
bool hasMinimumAmount = investorBalances[msg.sender].add(_amount) >= minimumContribution;
bool withinCap = totalInvestedInWei.add(_amount) <= cap;
return hasMinimumAmount && withinCap && nonZero;
}
//TESTED by Roman Storm
function whitelistInvestor(address _newInvestor) public onlyOwner {
if(!whitelist[_newInvestor]) {
whitelist[_newInvestor] = true;
investorsLength++;
}
}
//TESTED by Roman Storm
function whitelistInvestors(address[] _investors) external onlyOwner {
require(_investors.length <= 250);
for(uint8 i=0; i<_investors.length;i++) {
address newInvestor = _investors[i];
if(!whitelist[newInvestor]) {
whitelist[newInvestor] = true;
investorsLength++;
}
}
}
function blacklistInvestor(address _investor) public onlyOwner {
if(whitelist[_investor]) {
delete whitelist[_investor];
if(investorsLength != 0) {
investorsLength--;
}
}
}
} | TESTED by Roman Storm | function forwardFunds(uint256 _amount) internal {
vault.transfer(_amount);
}
| 948,048 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "./interface/IRatingOracle.sol";
contract DebtDerivative is Ownable, ERC1155 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct DebtDerivativeArgs {
address borrower;
address token;
uint256 amount;
uint256 loanDeadline;
}
struct DebtDerivativeInfo {
address delegator;
address borrower;
address token;
uint256 loanedAmount;
uint256 expecetedProfit;
uint256 expiration;
bool active;
}
address public oracleAddress;
// Likely will be only stablecoins whitelisted (DAI, USDC) or whichever Supertokens may be available
address[] public tokens;
uint256 public DEADLINE_INTERVALS = 4000;
uint256 public maxDeadline = 30 days;
// It could be updated along the system when credit trustworthy relation is created between users and protocol
uint256 public maxBorrowable = 100000 ether;
uint256 public nextDebtDerivativeId = 0;
mapping(uint256 => DebtDerivativeInfo) public derivateInfo;
mapping(address => bool) public whitelistedBorrower;
mapping(address => bool) public activeLoan;
event DerivativeDebtCreated(
uint256 id,
address borrower,
address token,
uint256 amount,
uint256 loanDeadline
);
constructor(string memory _uri, address _oracleAddress) ERC1155(_uri) {
oracleAddress = _oracleAddress;
}
/// @notice New URI for ERC1155 metadata
/// @param _newUri The new URI
function setURI(string memory _newUri) external onlyOwner {
_setURI(_newUri);
}
/// @notice Update max borrowable amount
/// @param _maxBorrowable New max amount to allow to be borrowed
function setMaxBorrowable(uint256 _maxBorrowable) external onlyOwner {
require(_maxBorrowable > maxBorrowable, "<maxBorrowable!");
maxBorrowable = _maxBorrowable;
}
/// @notice New borrower address to be whitelisted
/// @param _borrower Potential borrower address
function setWhitelistedBorrower(address _borrower) external onlyOwner {
whitelistedBorrower[_borrower] = true;
IRatingOracle(oracleAddress).initiliasedCreditInfo(_borrower);
}
/// @notice Set new borrowing cap
/// @param _newBorrowingCap The new borrowing max amount
function setWhitelistedBorrower(uint256 _newBorrowingCap)
external
onlyOwner
{
require(_newBorrowingCap > 0, "0!");
maxBorrowable = _newBorrowingCap;
}
/// @notice It will query in our oracle which is the user rating given
/// @param _borrower borrower who the system will check rating against
function maxAllowedBorrowerDeadline(address _borrower)
internal
returns (uint256)
{
uint256 borrowerRating = IRatingOracle(oracleAddress).getRating(
_borrower
);
uint256 deadline = 0;
if (borrowerRating <= 25) {
deadline = maxDeadline.mul(uint256(1000)).div(DEADLINE_INTERVALS);
} else if (borrowerRating > 25 && borrowerRating <= 50) {
deadline = maxDeadline.mul(uint256(2000)).div(DEADLINE_INTERVALS);
} else if (borrowerRating > 50 && borrowerRating <= 75) {
deadline = maxDeadline.mul(uint256(3000)).div(DEADLINE_INTERVALS);
} else {
deadline = maxDeadline;
}
require(deadline <= maxDeadline, ">maxDeadline");
return deadline;
}
/// @dev It will generate a new debt derivative ID with a specific deadline based on _borrower credit history check
/// @param _token Token which will be borrowed
/// @return The Debt Derivative ID
function createDebtDerivative(address _token) external returns (uint256) {
// likely it will be either voted via governance or after devs clasify the borrower as "safe", bias?
require(whitelistedBorrower[msg.sender], "notWhitelisted!");
uint256 borrowableAmount = IRatingOracle(oracleAddress)
.getMaxLoanAmount(msg.sender);
require(borrowableAmount <= maxBorrowable, ">maxBorrowable");
uint256 _loanDeadline = maxAllowedBorrowerDeadline(msg.sender);
DebtDerivativeArgs memory debtDerivativeArgs = DebtDerivativeArgs({
borrower: msg.sender,
token: _token,
amount: borrowableAmount,
loanDeadline: block.timestamp + _loanDeadline
});
return _generateDebtDerivative(debtDerivativeArgs);
}
/// @notice Generates the new erc1155 debt derivative representation
/// @param _args Debt derivative details to generate
/// @return The Debt Derivative ID
function _generateDebtDerivative(DebtDerivativeArgs memory _args)
internal
returns (uint256)
{
require(_args.amount > 0, "<0!");
require(!activeLoan[_args.borrower], "active!");
// The liquidity available probably needs to be accounted from those delegating to our system, but we should avoid to be idle in a internal pool
// Probably some sequencing as FIFO vibe to be able to grab the full amount requested by the borrower?. More tricky as for DebtDerivativeInfo struct
// multi delegator[] ??
uint256 _id = nextDebtDerivativeId;
IERC20(_args.token).safeApprove(_args.borrower, _args.amount);
IERC20(_args.token).safeTransferFrom(
_args.borrower,
address(this),
_args.amount
);
activeLoan[_args.borrower] = true;
derivateInfo[_id] = DebtDerivativeInfo({
delegator: address(0),
borrower: _args.borrower,
token: _args.token,
loanedAmount: _args.amount,
expecetedProfit: _args.amount.mul(uint256(600)).div(uint256(10000)),
expiration: block.timestamp.add(_args.loanDeadline),
active: true
});
_mint(_args.borrower, _id, _args.amount, "");
emit DerivativeDebtCreated(
_id,
_args.borrower,
_args.token,
_args.amount,
_args.loanDeadline
);
nextDebtDerivativeId = nextDebtDerivativeId.add(1);
return _id;
}
} | Update max borrowable amount _maxBorrowable New max amount to allow to be borrowed | function setMaxBorrowable(uint256 _maxBorrowable) external onlyOwner {
require(_maxBorrowable > maxBorrowable, "<maxBorrowable!");
maxBorrowable = _maxBorrowable;
}
| 14,049,095 |
//Address: 0x2dcd9b1a7ed408ff48bd4918a1f9c0535dc54ead
//Contract name: WeSingCoin223Token_11
//Balance: 0 Ether
//Verification Date: 5/25/2018
//Transacion Count: 230
// CODE STARTS HERE
pragma solidity ^0.4.23;
//pragma experimental ABIEncoderV2;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function safeMul(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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
//-------------------------------------------------------------------------------------
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract ERC223 is ERC20 {
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transferFrom(address from, address to, uint value, bytes data) public returns (bool ok);
}
/*
Base class contracts willing to accept ERC223 token transfers must conform to.
Sender: msg.sender to the token contract, the address originating the token transfer.
- For user originated transfers sender will be equal to tx.origin
- For contract originated transfers, tx.origin will be the user that made the tx that produced the transfer.
Origin: the origin address from whose balance the tokens are sent
- For transfer(), origin = msg.sender
- For transferFrom() origin = _from to token contract
Value is the amount of tokens sent
Data is arbitrary data sent with the token transfer. Simulates ether tx.data
From, origin and value shouldn't be trusted unless the token contract is trusted.
If sender == tx.origin, it is safe to trust it regardless of the token.
*/
contract ERC223Receiver {
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool ok);
}
contract Standard223Receiver is ERC223Receiver {
function supportsToken(address token) public view returns (bool);
}
//-------------------------------------------------------------------------------------
//Implementation
contract WeSingCoin223Token_11 is ERC20, ERC223, Standard223Receiver, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
address /*public*/ contrInitiator;
address /*public*/ thisContract;
bool /*public*/ isTokenSupport;
mapping(address => bool) isSendingLocked;
bool isAllTransfersLocked;
uint oneTransferLimit;
uint oneDayTransferLimit;
struct TransferInfo {
//address sender; //maybe use in the future
//address from; //no need because all this is kept in transferInfo[_from]
//address to; //maybe use in the future
uint256 value;
uint time;
}
struct TransferInfos {
mapping (uint => TransferInfo) ti;
uint tc;
}
mapping (address => TransferInfos) transferInfo;
//-------------------------------------------------------------------------------------
//from ExampleToken
constructor(/*uint initialBalance*/) public {
decimals = 6; // Amount of decimals for display purposes
name = "WeSingCoin"; // Set the name for display purposes
symbol = 'WSC'; // Set the symbol for display purposes
uint initialBalance = (10 ** uint256(decimals)) * 5000*1000*1000;
balances[msg.sender] = initialBalance;
totalSupply = initialBalance;
contrInitiator = msg.sender;
thisContract = this;
isTokenSupport = false;
isAllTransfersLocked = true;
oneTransferLimit = (10 ** uint256(decimals)) * 10*1000*1000;
oneDayTransferLimit = (10 ** uint256(decimals)) * 50*1000*1000;
// Ideally call token fallback here too
}
//-------------------------------------------------------------------------------------
//from StandardToken
function super_transfer(address _to, uint _value) /*public*/ internal returns (bool success) {
require(!isSendingLocked[msg.sender]);
require(_value <= oneTransferLimit);
require(balances[msg.sender] >= _value);
if(msg.sender == contrInitiator) {
//no restricton
} else {
require(!isAllTransfersLocked);
require(safeAdd(getLast24hSendingValue(msg.sender), _value) <= oneDayTransferLimit);
}
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
uint tc=transferInfo[msg.sender].tc;
transferInfo[msg.sender].ti[tc].value = _value;
transferInfo[msg.sender].ti[tc].time = now;
transferInfo[msg.sender].tc = safeAdd(transferInfo[msg.sender].tc, 1);
emit Transfer(msg.sender, _to, _value);
return true;
}
function super_transferFrom(address _from, address _to, uint _value) /*public*/ internal returns (bool success) {
require(!isSendingLocked[_from]);
require(_value <= oneTransferLimit);
require(balances[_from] >= _value);
if(msg.sender == contrInitiator && _from == thisContract) {
// no restriction
} else {
require(!isAllTransfersLocked);
require(safeAdd(getLast24hSendingValue(_from), _value) <= oneDayTransferLimit);
uint allowance = allowed[_from][msg.sender];
require(allowance >= _value);
allowed[_from][msg.sender] = safeSub(allowance, _value);
}
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
uint tc=transferInfo[_from].tc;
transferInfo[_from].ti[tc].value = _value;
transferInfo[_from].ti[tc].time = now;
transferInfo[_from].tc = safeAdd(transferInfo[_from].tc, 1);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
//-------------------------------------------------------------------------------------
//from Standard223Token
//function that is called when a user or another contract wants to transfer funds
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
//filtering if the target is a contract with bytecode inside it
if (!super_transfer(_to, _value)) assert(false); // do a normal token transfer
if (isContract(_to)) {
if(!contractFallback(msg.sender, _to, _value, _data)) assert(false);
}
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool success) {
if (!super_transferFrom(_from, _to, _value)) assert(false); // do a normal token transfer
if (isContract(_to)) {
if(!contractFallback(_from, _to, _value, _data)) assert(false);
}
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
return transfer(_to, _value, new bytes(0));
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
return transferFrom(_from, _to, _value, new bytes(0));
}
//function that is called when transaction target is a contract
function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool success) {
ERC223Receiver reciever = ERC223Receiver(_to);
return reciever.tokenFallback(msg.sender, _origin, _value, _data);
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
//-------------------------------------------------------------------------------------
//from Standard223Receiver
Tkn tkn;
struct Tkn {
address addr;
address sender;
address origin;
uint256 value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool ok) {
if (!supportsToken(msg.sender)) return false;
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
tkn = Tkn(msg.sender, _sender, _origin, _value, _data, getSig(_data));
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) return false;
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function getSig(bytes _data) private pure returns (bytes4 sig) {
uint l = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < l; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (l - 1 - i))));
}
}
bool __isTokenFallback;
modifier tokenPayable {
if (!__isTokenFallback) assert(false);
_; //_ is a special character used in modifiers
}
//function supportsToken(address token) public pure returns (bool); //moved up
//-------------------------------------------------------------------------------------
//from ExampleReceiver
/*
//we do not use dedicated function to receive Token in contract associated account
function foo(
//uint i
) tokenPayable public {
emit LogTokenPayable(1, tkn.addr, tkn.sender, tkn.value);
}
*/
function () tokenPayable public {
emit LogTokenPayable(0, tkn.addr, tkn.sender, tkn.value);
}
function supportsToken(address token) public view returns (bool) {
//do not need to to anything with that token address?
//if (token == 0) { //attila addition
if (token != thisContract) { //attila addition, support only our own token, not others' token
return false;
}
if(!isTokenSupport) { //attila addition
return false;
}
return true;
}
event LogTokenPayable(uint i, address token, address sender, uint value);
//-------------------------------------------------------------------------------------
// My extensions
/*
function enableTokenSupport(bool _tokenSupport) public returns (bool success) {
if(msg.sender == contrInitiator) {
isTokenSupport = _tokenSupport;
return true;
} else {
return false;
}
}
*/
function setIsAllTransfersLocked(bool _lock) public {
require(msg.sender == contrInitiator);
isAllTransfersLocked = _lock;
}
function setIsSendingLocked(address _from, bool _lock) public {
require(msg.sender == contrInitiator);
isSendingLocked[_from] = _lock;
}
function getIsAllTransfersLocked() public view returns (bool ok) {
return isAllTransfersLocked;
}
function getIsSendingLocked(address _from ) public view returns (bool ok) {
return isSendingLocked[_from];
}
/*
function getTransferInfoCount(address _from) public view returns (uint count) {
return transferInfo[_from].tc;
}
*/
/*
// use experimental feature
function getTransferInfo(address _from, uint index) public view returns (TransferInfo ti) {
return transferInfo[_from].ti[index];
}
*/
/*
function getTransferInfoTime(address _from, uint index) public view returns (uint time) {
return transferInfo[_from].ti[index].time;
}
*/
/*
function getTransferInfoValue(address _from, uint index) public view returns (uint value) {
return transferInfo[_from].ti[index].value;
}
*/
function getLast24hSendingValue(address _from) public view returns (uint totVal) {
totVal = 0; //declared above;
uint tc = transferInfo[_from].tc;
if(tc > 0) {
for(uint i = tc-1 ; i >= 0 ; i--) {
// if(now - transferInfo[_from].ti[i].time < 10 minutes) {
// if(now - transferInfo[_from].ti[i].time < 1 hours) {
if(now - transferInfo[_from].ti[i].time < 1 days) {
totVal = safeAdd(totVal, transferInfo[_from].ti[i].value );
} else {
break;
}
}
}
}
function airdropIndividual(address[] _recipients, uint256[] _values, uint256 _elemCount, uint _totalValue) public returns (bool success) {
require(_recipients.length == _elemCount);
require(_values.length == _elemCount);
require(_elemCount <= 50);
uint256 totalValue = 0;
for(uint i = 0; i< _recipients.length; i++) {
totalValue = safeAdd(totalValue, _values[i]);
}
require(totalValue == _totalValue);
for(i = 0; i< _recipients.length; i++) {
transfer(_recipients[i], _values[i]);
}
return true;
}
}
| / use experimental feature | function getTransferInfo(address _from, uint index) public view returns (TransferInfo ti) {
return transferInfo[_from].ti[index];
}
| 5,395,823 |
./full_match/3/0xaC6F70f8deCaa9767a75D66B02Fe2fdd0d3a5a02/sources/https_/github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol | Required interface of an ERC721 compliant contract./function safeTransferFrom(address from, address to, uint256 tokenId) external;function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; | 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 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);
}
| 14,137,005 |
pragma solidity ^0.4.20;
contract Election {
// Represents a Candidate in the election
struct Candidate {
bytes32 name;
uint voteCount;
}
// Represents a single voter
// voted specifies if they have already voted
// voteIndex specifies who they voted for
// weight makes sure only people we authorize can vote
struct Voter {
bool voted;
uint voteIndex;
uint weight;
}
// This address represents the person who created the contract
// and who can authorize voters
address public owner;
// Name of the election
string public name;
// Hash table which represents an address and voter object
// The address is the address of the Voter
mapping(address => Voter) public voters;
// public list of Candidate's in the election
Candidate[] public candidates;
uint public electionEnd;
event ElectionResult(bytes32 name, uint voteCount);
function getElectionName() constant returns(string) {
return name;
}
// Constructor
function Election(string _name, uint durationMin, bytes32[] candidateLst) {
owner = msg.sender;
name = _name;
// the 'now' variable is the creation time of the current block
electionEnd = now + (durationMin * 1 minutes);
for(uint x=0; x < candidateLst.length; x++) {
candidates.push(Candidate(candidateLst[x], 0));
}
}
// voteIndex is the index of the candidate in the list
function vote(uint voteIndex) {
// Make sure election has not ended
require(now < electionEnd);
// Make sure voter has not already voted
require(!voters[msg.sender].voted);
candidates[voteIndex].voteCount += voters[msg.sender].weight;
voters[msg.sender].voteIndex = voteIndex;
voters[msg.sender].voted = true;
}
function authorizeVoters(address[] _voters) {
// Ensure only the owner can authorize users
require(msg.sender == owner);
for(uint x=0; x < _voters.length; x++) {
address voter = _voters[x];
if(!voters[voter].voted) {
voters[voter].weight = 1;
} else {
continue;
}
}
}
function electionResult() {
// Ensure only owner can see result
require(msg.sender == owner);
// Ensure election is actually over
require(now >= electionEnd);
for(uint x=0; x < candidates.length; x++) {
ElectionResult(candidates[x].name, candidates[x].voteCount);
}
}
function getCandidatesCount() public constant returns(uint) {
return candidates.length;
}
function getUser(uint index) public constant returns(bytes32, uint) {
return (candidates[index].name, candidates[index].voteCount);
}
}
| voteIndex is the index of the candidate in the list Make sure election has not ended Make sure voter has not already voted | function vote(uint voteIndex) {
require(now < electionEnd);
require(!voters[msg.sender].voted);
candidates[voteIndex].voteCount += voters[msg.sender].weight;
voters[msg.sender].voteIndex = voteIndex;
voters[msg.sender].voted = true;
}
| 2,550,736 |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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;
}
}
contract TokenReceiver {
/**
* @dev Method to be triggerred during approveAndCall execution
* @param _sender A wallet that initiated the operation
* @param _value Amount of approved tokens
* @param _data Additional arguments
*/
function tokenFallback(address _sender, uint256 _value, bytes _data) external returns (bool);
}
/**
* @title Timestamped
* @dev Timestamped contract has a separate method for receiving current timestamp.
* This simplifies derived contracts testability.
*/
contract Timestamped {
/**
* @dev Returns current timestamp.
*/
function _currentTime() internal view returns(uint256) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title 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
* 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;
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @title FlipNpikToken
* @dev The FlipNpikToken is a ERC20 token
*/
contract FlipNpikToken is Timestamped, StandardToken, DetailedERC20, HasNoEther {
using SafeMath for uint256;
// A wallet that will hold tokens
address public mainWallet;
// A wallet that is required to unlock reserve tokens
address public financeWallet;
// Locked reserve tokens amount is 500M FNP
uint256 public reserveSize = uint256(500000000).mul(10 ** 18);
// List of signatures required to unlock reserve tokens
mapping (address => bool) public reserveHolders;
// Total amount of unlocked reserve tokens
uint256 public totalUnlocked = 0;
// Scheduled for minting reserve tokens amount is 575M FNP
uint256 public mintSize = uint256(575000000).mul(10 ** 18);
// Datetime when minting according to schedule becomes available
uint256 public mintStart;
// Total amount of minted reserve tokens
uint256 public totalMinted = 0;
/**
* Describes minting stage structure fields
* @param start Minting stage start date
* @param volumt Total tokens available for the stage
*/
struct MintStage {
uint256 start;
uint256 volume;
}
// Array of stages
MintStage[] public stages;
/**
* @dev Event for reserve tokens minting operation logging
* @param _amount Amount minted
*/
event MintReserveLog(uint256 _amount);
/**
* @dev Event for reserve tokens unlock operation logging
* @param _amount Amount unlocked
*/
event UnlockReserveLog(uint256 _amount);
/**
* @param _mintStart Datetime when minting according to schedule becomes available
* @param _mainWallet A wallet that will hold tokens
* @param _financeWallet A wallet that is required to unlock reserve tokens
* @param _owner Smart contract owner address
*/
constructor (uint256 _mintStart, address _mainWallet, address _financeWallet, address _owner)
DetailedERC20("FlipNpik", "FNP", 18) public {
require(_mainWallet != address(0), "Main address is invalid.");
mainWallet = _mainWallet;
require(_financeWallet != address(0), "Finance address is invalid.");
financeWallet = _financeWallet;
require(_owner != address(0), "Owner address is invalid.");
owner = _owner;
_setStages(_mintStart);
_setReserveHolders();
// 425M FNP should be minted initially
_mint(uint256(425000000).mul(10 ** 18));
}
/**
* @dev Mints reserved tokens
*/
function mintReserve() public onlyOwner {
require(mintStart < _currentTime(), "Minting has not been allowed yet.");
require(totalMinted < mintSize, "No tokens are available for minting.");
// Get stage based on current datetime
MintStage memory currentStage = _getCurrentStage();
// Get amount available for minting
uint256 mintAmount = currentStage.volume.sub(totalMinted);
if (mintAmount > 0 && _mint(mintAmount)) {
emit MintReserveLog(mintAmount);
totalMinted = totalMinted.add(mintAmount);
}
}
/**
* @dev Unlocks reserve
*/
function unlockReserve() public {
require(msg.sender == owner || msg.sender == financeWallet, "Operation is not allowed for the wallet.");
require(totalUnlocked < reserveSize, "Reserve has been unlocked.");
// Save sender's signature for reserve tokens unlock
reserveHolders[msg.sender] = true;
if (_isReserveUnlocked() && _mint(reserveSize)) {
emit UnlockReserveLog(reserveSize);
totalUnlocked = totalUnlocked.add(reserveSize);
}
}
/**
* @dev Executes regular token approve operation and trigger receiver SC accordingly
* @param _to Address (SC) that should receive approval and be triggerred
* @param _value Amount of tokens for approve operation
* @param _data Additional arguments to be passed to the contract
*/
function approveAndCall(address _to, uint256 _value, bytes _data) public returns(bool) {
require(super.approve(_to, _value), "Approve operation failed.");
// Check if destination address is SC
if (isContract(_to)) {
TokenReceiver receiver = TokenReceiver(_to);
return receiver.tokenFallback(msg.sender, _value, _data);
}
return true;
}
/**
* @dev Mints tokens to main wallet balance
* @param _amount Amount to be minted
*/
function _mint(uint256 _amount) private returns(bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[mainWallet] = balances[mainWallet].add(_amount);
emit Transfer(address(0), mainWallet, _amount);
return true;
}
/**
* @dev Configures minting stages
* @param _mintStart Datetime when minting according to schedule becomes available
*/
function _setStages(uint256 _mintStart) private {
require(_mintStart >= _currentTime(), "Mint start date is invalid.");
mintStart = _mintStart;
stages.push(MintStage(_mintStart, uint256(200000000).mul(10 ** 18)));
stages.push(MintStage(_mintStart.add(365 days), uint256(325000000).mul(10 ** 18)));
stages.push(MintStage(_mintStart.add(2 * 365 days), uint256(450000000).mul(10 ** 18)));
stages.push(MintStage(_mintStart.add(3 * 365 days), uint256(575000000).mul(10 ** 18)));
}
/**
* @dev Configures unlock signature holders list
*/
function _setReserveHolders() private {
reserveHolders[mainWallet] = false;
reserveHolders[financeWallet] = false;
}
/**
* @dev Finds current stage parameters according to the rules and current date and time
* @return Current stage parameters (stage start date and available volume of tokens)
*/
function _getCurrentStage() private view returns (MintStage) {
uint256 index = 0;
uint256 time = _currentTime();
MintStage memory result;
while (index < stages.length) {
MintStage memory activeStage = stages[index];
if (time >= activeStage.start) {
result = activeStage;
}
index++;
}
return result;
}
/**
* @dev Checks if an address is a SC
*/
function isContract(address _addr) private view returns (bool) {
uint256 size;
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
/**
* @dev Checks if reserve tokens have all required signatures for unlock operation
*/
function _isReserveUnlocked() private view returns(bool) {
return reserveHolders[owner] == reserveHolders[financeWallet] && reserveHolders[owner];
}
} | Configures unlock signature holders list/ | function _setReserveHolders() private {
reserveHolders[mainWallet] = false;
reserveHolders[financeWallet] = false;
}
| 303,329 |
pragma solidity 0.6.2;
interface SmartWalletInterface {
function MIGRATESAITODAI348() external; //inject NONSTANDARD NAMING
function MIGRATECSAITODDAI449() external; //inject NONSTANDARD NAMING
function MIGRATECDAITODDAI856() external; //inject NONSTANDARD NAMING
function MIGRATECUSDCTODUSDC603() external; //inject NONSTANDARD NAMING
}
contract DTokenMigrator {
function BATCHMIGRATESAITODAI965(SmartWalletInterface[] calldata wallets) external { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < wallets.length; i++) {
if (gasleft() < 400000) {
break;
}
try wallets[i].MIGRATESAITODAI348() {} catch {}
}
}
function BATCHMIGRATECSAITODDAI402(SmartWalletInterface[] calldata wallets) external { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < wallets.length; i++) {
if (gasleft() < 600000) {
break;
}
try wallets[i].MIGRATECSAITODDAI449() {} catch {}
}
}
function BATCHMIGRATECDAITODDAI177(SmartWalletInterface[] calldata wallets) external { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < wallets.length; i++) {
if (gasleft() < 200000) {
break;
}
try wallets[i].MIGRATECDAITODDAI856() {} catch {}
}
}
function BATCHMIGRATECUSDCTODUSDC363(SmartWalletInterface[] calldata wallets) external { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < wallets.length; i++) {
if (gasleft() < 200000) {
break;
}
try wallets[i].MIGRATECUSDCTODUSDC603() {} catch {}
}
}
} | inject NONSTANDARD NAMING | function BATCHMIGRATESAITODAI965(SmartWalletInterface[] calldata wallets) external { | 1,074,346 |
// Dependency file: @openzeppelin/as/utils/Address.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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 as 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);
}
}
}
}
// Dependency file: as/interfaces/ISetValuer.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
// Dependency file: as/interfaces/IPriceOracle.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// Dependency file: @openzeppelin/as/token/ERC20/SafeERC20.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
// import "./IERC20.sol";
// import "../../math/SafeMath.sol";
// import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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");
}
}
}
// Dependency file: @openzeppelin/as/math/SignedSafeMath.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// Dependency file: as/protocol/lib/ResourceIdentifier.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// import { IController } from "../../interfaces/IController.sol";
// import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
// import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
// import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource as in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// Dependency file: as/interfaces/IModule.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// Dependency file: as/lib/ExplicitERC20.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
// import { SafeERC20 } from "@openzeppelin/as/token/ERC20/SafeERC20.sol";
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
// Dependency file: as/lib/PreciseUnitMath.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/as/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
// Dependency file: as/protocol/lib/Position.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
// import { SafeCast } from "@openzeppelin/as/utils/SafeCast.sol";
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/as/math/SignedSafeMath.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
// Dependency file: as/protocol/lib/ModuleBase.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
// import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
// import { IController } from "../../interfaces/IController.sol";
// import { IModule } from "../../interfaces/IModule.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { Invoke } from "./Invoke.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
// import { ResourceIdentifier } from "./ResourceIdentifier.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using PreciseUnitMath for uint256;
using Invoke for ISetToken;
using ResourceIdentifier for IController;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
// Dependency file: as/interfaces/IWrapAdapter.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title IWrapAdapter
* @author Set Protocol
*
*/
interface IWrapAdapter {
function ETH_TOKEN_ADDRESS() external view returns (address);
function getWrapCallData(
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits
) external view returns (address _subject, uint256 _value, bytes memory _calldata);
function getUnwrapCallData(
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedTokenUnits
) external view returns (address _subject, uint256 _value, bytes memory _calldata);
function getSpenderAddress(address _underlyingToken, address _wrappedToken) external view returns(address);
}
// Dependency file: as/interfaces/external/IWETH.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
// Dependency file: as/interfaces/ISetToken.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// Dependency file: as/protocol/lib/Invoke.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
// Dependency file: as/interfaces/IIntegrationRegistry.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
// Dependency file: as/interfaces/IController.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
// pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// Dependency file: @openzeppelin/as/math/SafeMath.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/as/utils/SafeCast.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// Dependency file: @openzeppelin/as/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
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;
}
}
// Dependency file: @openzeppelin/as/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/as/token/ERC20/IERC20.sol";
// import { ReentrancyGuard } from "@openzeppelin/as/utils/ReentrancyGuard.sol";
// import { SafeCast } from "@openzeppelin/as/utils/SafeCast.sol";
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
// import { IController } from "../../interfaces/IController.sol";
// import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
// import { Invoke } from "../lib/Invoke.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { IWETH } from "../../interfaces/external/IWETH.sol";
// import { IWrapAdapter } from "../../interfaces/IWrapAdapter.sol";
// import { ModuleBase } from "../lib/ModuleBase.sol";
// import { Position } from "../lib/Position.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title WrapModule
* @author Set Protocol
*
* Module that enables the wrapping of ERC20 and Ether positions via third party protocols. The WrapModule
* works in conjunction with WrapAdapters, in which the wrapAdapterID / integrationNames are stored on the
* integration registry.
*
* Some examples of wrap actions include wrapping, DAI to cDAI (Compound) or Dai to aDai (AAVE).
*/
contract WrapModule is ModuleBase, ReentrancyGuard {
using SafeCast for int256;
using PreciseUnitMath for uint256;
using Position for uint256;
using SafeMath for uint256;
using Invoke for ISetToken;
using Position for ISetToken.Position;
using Position for ISetToken;
/* ============ Events ============ */
event ComponentWrapped(
ISetToken indexed _setToken,
address indexed _underlyingToken,
address indexed _wrappedToken,
uint256 _underlyingQuantity,
uint256 _wrappedQuantity,
string _integrationName
);
event ComponentUnwrapped(
ISetToken indexed _setToken,
address indexed _underlyingToken,
address indexed _wrappedToken,
uint256 _underlyingQuantity,
uint256 _wrappedQuantity,
string _integrationName
);
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public weth;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* MANAGER-ONLY: Instructs the SetToken to wrap an underlying asset into a wrappedToken via a specified adapter.
*
* @param _setToken Instance of the SetToken
* @param _underlyingToken Address of the component to be wrapped
* @param _wrappedToken Address of the desired wrapped token
* @param _underlyingUnits Quantity of underlying units in Position units
* @param _integrationName Name of wrap module integration (mapping on integration registry)
*/
function wrap(
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits,
string calldata _integrationName
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
(
uint256 notionalUnderlyingWrapped,
uint256 notionalWrapped
) = _validateWrapAndUpdate(
_integrationName,
_setToken,
_underlyingToken,
_wrappedToken,
_underlyingUnits,
false // does not use Ether
);
emit ComponentWrapped(
_setToken,
_underlyingToken,
_wrappedToken,
notionalUnderlyingWrapped,
notionalWrapped,
_integrationName
);
}
/**
* MANAGER-ONLY: Instructs the SetToken to wrap Ether into a wrappedToken via a specified adapter. Since SetTokens
* only hold WETH, in order to support protocols that collateralize with Ether the SetToken's WETH must be unwrapped
* first before sending to the external protocol.
*
* @param _setToken Instance of the SetToken
* @param _wrappedToken Address of the desired wrapped token
* @param _underlyingUnits Quantity of underlying units in Position units
* @param _integrationName Name of wrap module integration (mapping on integration registry)
*/
function wrapWithEther(
ISetToken _setToken,
address _wrappedToken,
uint256 _underlyingUnits,
string calldata _integrationName
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
(
uint256 notionalUnderlyingWrapped,
uint256 notionalWrapped
) = _validateWrapAndUpdate(
_integrationName,
_setToken,
address(weth),
_wrappedToken,
_underlyingUnits,
true // uses Ether
);
emit ComponentWrapped(
_setToken,
address(weth),
_wrappedToken,
notionalUnderlyingWrapped,
notionalWrapped,
_integrationName
);
}
/**
* MANAGER-ONLY: Instructs the SetToken to unwrap a wrapped asset into its underlying via a specified adapter.
*
* @param _setToken Instance of the SetToken
* @param _underlyingToken Address of the underlying asset
* @param _wrappedToken Address of the component to be unwrapped
* @param _wrappedUnits Quantity of wrapped tokens in Position units
* @param _integrationName ID of wrap module integration (mapping on integration registry)
*/
function unwrap(
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedUnits,
string calldata _integrationName
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
(
uint256 notionalUnderlyingUnwrapped,
uint256 notionalUnwrapped
) = _validateUnwrapAndUpdate(
_integrationName,
_setToken,
_underlyingToken,
_wrappedToken,
_wrappedUnits,
false // uses Ether
);
emit ComponentUnwrapped(
_setToken,
_underlyingToken,
_wrappedToken,
notionalUnderlyingUnwrapped,
notionalUnwrapped,
_integrationName
);
}
/**
* MANAGER-ONLY: Instructs the SetToken to unwrap a wrapped asset collateralized by Ether into Wrapped Ether. Since
* external protocol will send back Ether that Ether must be Wrapped into WETH in order to be accounted for by SetToken.
*
* @param _setToken Instance of the SetToken
* @param _wrappedToken Address of the component to be unwrapped
* @param _wrappedUnits Quantity of wrapped tokens in Position units
* @param _integrationName ID of wrap module integration (mapping on integration registry)
*/
function unwrapWithEther(
ISetToken _setToken,
address _wrappedToken,
uint256 _wrappedUnits,
string calldata _integrationName
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
(
uint256 notionalUnderlyingUnwrapped,
uint256 notionalUnwrapped
) = _validateUnwrapAndUpdate(
_integrationName,
_setToken,
address(weth),
_wrappedToken,
_wrappedUnits,
true // uses Ether
);
emit ComponentUnwrapped(
_setToken,
address(weth),
_wrappedToken,
notionalUnderlyingUnwrapped,
notionalUnwrapped,
_integrationName
);
}
/**
* Initializes this module to the SetToken. Only callable by the SetToken's manager.
*
* @param _setToken Instance of the SetToken to issue
*/
function initialize(ISetToken _setToken) external onlySetManager(_setToken, msg.sender) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken.
*/
function removeModule() external override {}
/* ============ Internal Functions ============ */
/**
* Validates the wrap operation is valid. In particular, the following checks are made:
* - The position is Default
* - The position has sufficient units given the transact quantity
* - The transact quantity > 0
*
* It is expected that the adapter will check if wrappedToken/underlyingToken are a valid pair for the given
* integration.
*/
function _validateInputs(
ISetToken _setToken,
address _transactPosition,
uint256 _transactPositionUnits
)
internal
view
{
require(_transactPositionUnits > 0, "Target position units must be > 0");
require(_setToken.hasDefaultPosition(_transactPosition), "Target default position must be component");
require(
_setToken.hasSufficientDefaultUnits(_transactPosition, _transactPositionUnits),
"Unit cant be greater than existing"
);
}
/**
* The WrapModule calculates the total notional underlying to wrap, approves the underlying to the 3rd party
* integration contract, then invokes the SetToken to call wrap by passing its calldata along. When raw ETH
* is being used (_usesEther = true) WETH position must first be unwrapped and underlyingAddress sent to
* adapter must be external protocol's ETH representative address.
*
* Returns notional amount of underlying tokens and wrapped tokens that were wrapped.
*/
function _validateWrapAndUpdate(
string calldata _integrationName,
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits,
bool _usesEther
)
internal
returns (uint256, uint256)
{
_validateInputs(_setToken, _underlyingToken, _underlyingUnits);
// Snapshot pre wrap balances
(
uint256 preActionUnderlyingNotional,
uint256 preActionWrapNotional
) = _snapshotTargetAssetsBalance(_setToken, _underlyingToken, _wrappedToken);
uint256 notionalUnderlying = _setToken.totalSupply().getDefaultTotalNotional(_underlyingUnits);
IWrapAdapter wrapAdapter = IWrapAdapter(getAndValidateAdapter(_integrationName));
// Execute any pre-wrap actions depending on if using raw ETH or not
if (_usesEther) {
_setToken.invokeUnwrapWETH(address(weth), notionalUnderlying);
} else {
address spender = wrapAdapter.getSpenderAddress(_underlyingToken, _wrappedToken);
_setToken.invokeApprove(_underlyingToken, spender, notionalUnderlying);
}
// Get function call data and invoke on SetToken
_createWrapDataAndInvoke(
_setToken,
wrapAdapter,
_usesEther ? wrapAdapter.ETH_TOKEN_ADDRESS() : _underlyingToken,
_wrappedToken,
notionalUnderlying
);
// Snapshot post wrap balances
(
uint256 postActionUnderlyingNotional,
uint256 postActionWrapNotional
) = _snapshotTargetAssetsBalance(_setToken, _underlyingToken, _wrappedToken);
_updatePosition(_setToken, _underlyingToken, preActionUnderlyingNotional, postActionUnderlyingNotional);
_updatePosition(_setToken, _wrappedToken, preActionWrapNotional, postActionWrapNotional);
return (
preActionUnderlyingNotional.sub(postActionUnderlyingNotional),
postActionWrapNotional.sub(preActionWrapNotional)
);
}
/**
* The WrapModule calculates the total notional wrap token to unwrap, then invokes the SetToken to call
* unwrap by passing its calldata along. When raw ETH is being used (_usesEther = true) underlyingAddress
* sent to adapter must be set to external protocol's ETH representative address and ETH returned from
* external protocol is wrapped.
*
* Returns notional amount of underlying tokens and wrapped tokens unwrapped.
*/
function _validateUnwrapAndUpdate(
string calldata _integrationName,
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedTokenUnits,
bool _usesEther
)
internal
returns (uint256, uint256)
{
_validateInputs(_setToken, _wrappedToken, _wrappedTokenUnits);
(
uint256 preActionUnderlyingNotional,
uint256 preActionWrapNotional
) = _snapshotTargetAssetsBalance(_setToken, _underlyingToken, _wrappedToken);
uint256 notionalWrappedToken = _setToken.totalSupply().getDefaultTotalNotional(_wrappedTokenUnits);
IWrapAdapter wrapAdapter = IWrapAdapter(getAndValidateAdapter(_integrationName));
// Get function call data and invoke on SetToken
_createUnwrapDataAndInvoke(
_setToken,
wrapAdapter,
_usesEther ? wrapAdapter.ETH_TOKEN_ADDRESS() : _underlyingToken,
_wrappedToken,
notionalWrappedToken
);
if (_usesEther) {
_setToken.invokeWrapWETH(address(weth), address(_setToken).balance);
}
(
uint256 postActionUnderlyingNotional,
uint256 postActionWrapNotional
) = _snapshotTargetAssetsBalance(_setToken, _underlyingToken, _wrappedToken);
_updatePosition(_setToken, _underlyingToken, preActionUnderlyingNotional, postActionUnderlyingNotional);
_updatePosition(_setToken, _wrappedToken, preActionWrapNotional, postActionWrapNotional);
return (
postActionUnderlyingNotional.sub(preActionUnderlyingNotional),
preActionWrapNotional.sub(postActionWrapNotional)
);
}
/**
* Create the calldata for wrap and then invoke the call on the SetToken.
*/
function _createWrapDataAndInvoke(
ISetToken _setToken,
IWrapAdapter _wrapAdapter,
address _underlyingToken,
address _wrappedToken,
uint256 _notionalUnderlying
) internal {
(
address callTarget,
uint256 callValue,
bytes memory callByteData
) = _wrapAdapter.getWrapCallData(
_underlyingToken,
_wrappedToken,
_notionalUnderlying
);
_setToken.invoke(callTarget, callValue, callByteData);
}
/**
* Create the calldata for unwrap and then invoke the call on the SetToken.
*/
function _createUnwrapDataAndInvoke(
ISetToken _setToken,
IWrapAdapter _wrapAdapter,
address _underlyingToken,
address _wrappedToken,
uint256 _notionalUnderlying
) internal {
(
address callTarget,
uint256 callValue,
bytes memory callByteData
) = _wrapAdapter.getUnwrapCallData(
_underlyingToken,
_wrappedToken,
_notionalUnderlying
);
_setToken.invoke(callTarget, callValue, callByteData);
}
/**
* After a wrap/unwrap operation, check the underlying and wrap token quantities and recalculate
* the units ((total tokens - airdrop)/ total supply). Then update the position on the SetToken.
*/
function _updatePosition(
ISetToken _setToken,
address _token,
uint256 _preActionTokenBalance,
uint256 _postActionTokenBalance
) internal {
uint256 newUnit = _setToken.totalSupply().calculateDefaultEditPositionUnit(
_preActionTokenBalance,
_postActionTokenBalance,
_setToken.getDefaultPositionRealUnit(_token).toUint256()
);
_setToken.editDefaultPosition(_token, newUnit);
}
/**
* Take snapshot of SetToken's balance of underlying and wrapped tokens.
*/
function _snapshotTargetAssetsBalance(
ISetToken _setToken,
address _underlyingToken,
address _wrappedToken
) internal view returns(uint256, uint256) {
uint256 underlyingTokenBalance = IERC20(_underlyingToken).balanceOf(address(_setToken));
uint256 wrapTokenBalance = IERC20(_wrappedToken).balanceOf(address(_setToken));
return (
underlyingTokenBalance,
wrapTokenBalance
);
}
} | IWETH Set Protocol Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal functionality./ | interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
Copyright 2018 Set Labs Inc.
}
| 12,564,849 |
./partial_match/1/0xA2608594E83CB2913333Ff1fe6e1cC4EA66484f5/sources/src/TokenVesting.sol | Computes the vested amount of tokens for the given vesting schedule identifier. return the vested amount/ | function computeReleasableAmount(
bytes32 vestingScheduleId
)
external
view
onlyIfVestingScheduleNotRevoked(vestingScheduleId)
returns (uint256)
{
VestingSchedule storage vestingSchedule = vestingSchedules[
vestingScheduleId
];
return _computeReleasableAmount(vestingSchedule);
}
| 2,747,852 |
/*
* Crypto stamp Collection-Create ENS Subdomain registrar
* Simple ENS subdomain registrar to be used for Crypto stamp Collections,
* with functionality to actually create ollections as well.
*
* Developed by Capacity Blockchain Solutions GmbH <capacity.at>
* for Österreichische Post AG <post.at>
*
* Any usage of or interaction with this set of contracts is subject to the
* Terms & Conditions available at https://crypto.post.at/
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// File: @openzeppelin/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);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
/**
* @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: contracts/ENSReverseRegistrarI.sol
/*
* Interfaces for ENS Reverse Registrar
* See https://github.com/ensdomains/ens/blob/master/contracts/ReverseRegistrar.sol for full impl
* Also see https://github.com/wealdtech/wealdtech-solidity/blob/master/contracts/ens/ENSReverseRegister.sol
*
* Use this as follows (registryAddress is the address of the ENS registry to use):
* -----
* // This hex value is caclulated by namehash('addr.reverse')
* bytes32 public constant ENS_ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
* function registerReverseENS(address registryAddress, string memory calldata) external {
* require(registryAddress != address(0), "need a valid registry");
* address reverseRegistrarAddress = ENSRegistryOwnerI(registryAddress).owner(ENS_ADDR_REVERSE_NODE)
* require(reverseRegistrarAddress != address(0), "need a valid reverse registrar");
* ENSReverseRegistrarI(reverseRegistrarAddress).setName(name);
* }
* -----
* or
* -----
* function registerReverseENS(address reverseRegistrarAddress, string memory calldata) external {
* require(reverseRegistrarAddress != address(0), "need a valid reverse registrar");
* ENSReverseRegistrarI(reverseRegistrarAddress).setName(name);
* }
* -----
* ENS deployments can be found at https://docs.ens.domains/ens-deployments
* E.g. Etherscan can be used to look up that owner on those contracts.
* namehash.hash("addr.reverse") == "0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2"
* Ropsten: ens.owner(namehash.hash("addr.reverse")) == "0x6F628b68b30Dc3c17f345c9dbBb1E483c2b7aE5c"
* Mainnet: ens.owner(namehash.hash("addr.reverse")) == "0x084b1c3C81545d370f3634392De611CaaBFf8148"
*/
interface ENSRegistryOwnerI {
function owner(bytes32 node) external view returns (address);
}
interface ENSReverseRegistrarI {
event NameChanged(bytes32 indexed node, string name);
/**
* @dev Sets the `name()` record for the reverse ENS record associated with
* the calling account.
* @param name The name to set for this address.
* @return The ENS node hash of the reverse record.
*/
function setName(string calldata name) external returns (bytes32);
}
// File: contracts/BridgeDataI.sol
/*
* Interface for data storage of the bridge.
*/
interface BridgeDataI {
event AddressChanged(string name, address previousAddress, address newAddress);
event ConnectedChainChanged(string previousConnectedChainName, string newConnectedChainName);
event TokenURIBaseChanged(string previousTokenURIBase, string newTokenURIBase);
event TokenSunsetAnnounced(uint256 indexed timestamp);
/**
* @dev The name of the chain connected to / on the other side of this bridge head.
*/
function connectedChainName() external view returns (string memory);
/**
* @dev The name of our own chain, used in token URIs handed to deployed tokens.
*/
function ownChainName() external view returns (string memory);
/**
* @dev The base of ALL token URIs, e.g. https://example.com/
*/
function tokenURIBase() external view returns (string memory);
/**
* @dev The sunset timestamp for all deployed tokens.
* If 0, no sunset is in place. Otherwise, if older than block timestamp,
* all transfers of the tokens are frozen.
*/
function tokenSunsetTimestamp() external view returns (uint256);
/**
* @dev Set a token sunset timestamp.
*/
function setTokenSunsetTimestamp(uint256 _timestamp) external;
/**
* @dev Set an address for a name.
*/
function setAddress(string memory name, address newAddress) external;
/**
* @dev Get an address for a name.
*/
function getAddress(string memory name) external view returns (address);
}
// File: contracts/ENS.sol
/*
* ENS interface
* https://github.com/ensdomains/ens/blob/master/contracts/ENS.sol with update to Solidity 0.8 pragma,
* `owner` parameters renamed to `nodeOwner` to silence compiler warnings of shadowing.
*/
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed nodeOwner, address indexed operator, bool approved);
function setRecord(bytes32 node, address nodeOwner, address resolver, uint64 ttl) external;
function setSubnodeRecord(bytes32 node, bytes32 label, address nodeOwner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address nodeOwner) external returns(bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address nodeOwner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address nodeOwner, address operator) external view returns (bool);
}
// File: contracts/ENSSimpleRegistrarI.sol
/*
* Interface for simple ENS Registrar
* Exposing a registerAddr() signature modeled after the sample at
* https://docs.ens.domains/contract-developer-guide/writing-a-registrar
* together with the setAddr() from the AddrResolver.
*/
interface ENSSimpleRegistrarI {
function registerAddr(bytes32 label, address target) external;
}
// File: contracts/ENSAddrResolverI.sol
/*
* Interface for ENS Addr Resolver
* Exposing the setAddr() signature used by the public resolver for Ethereum names
*/
interface ENSAddrResolverI {
event AddrChanged(bytes32 indexed node, address a);
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param a The address to set.
*/
function setAddr(bytes32 node, address a) external;
}
// File: contracts/CollectionsL1CreateI.sol
/*
* Interface for create functionality of the Collections factory.
*/
/**
* @dev Create-related interface of a Collections contract.
*/
interface CollectionsL1CreateI {
/**
* @dev Emitted when a new collection is created.
*/
event NewCollection(address indexed owner, address collectionAddress);
/**
* @dev Transfer createControl key to someone else.
*/
function transferCreateControl(address _newCreateControl) external;
/**
* @dev Creates a new Collection. For calling from other contracts,
* returns the address of the new Collection.
*/
function create(address _notificationContract,
string calldata _ensName,
string calldata _ensSubdomainName,
address _ensSubdomainRegistrarAddress,
address _ensReverseRegistrarAddress)
external;
/**
* @dev Create a collection for a different owner. Only callable by a
* create controller role. For calling from other contracts, returns the
* address of the new Collection.
*/
function createFor(address payable _newOwner,
address _notificationContract,
string calldata _ensName,
string calldata _ensSubdomainName,
address _ensSubdomainRegistrarAddress,
address _ensReverseRegistrarAddress)
external payable;
}
// File: contracts/CollCreateENSRegistrar.sol
/*
* An ENS Registrar that also takes care of creating Collections.
*/
contract CollCreateENSRegistrar is ENSSimpleRegistrarI {
BridgeDataI public bridgeData;
ENS public ens;
ENSAddrResolverI public resolver;
bytes32 public rootNode;
bool createInProgress;
event BridgeDataChanged(address indexed previousBridgeData, address indexed newBridgeData);
event DefaultResolverChanged(address indexed previousResolverAddress, address indexed newResolverAddress);
event Registered(bytes32 indexed label, bytes32 subnode, address indexed target);
event Unregistered(bytes32 indexed label, bytes32 subnode);
event Blocked(bytes32 indexed label, bytes32 subnode);
constructor(address _bridgeDataAddress, address _ensAddress, address _ensResolverAddress, bytes32 _rootNode)
{
bridgeData = BridgeDataI(_bridgeDataAddress);
require(address(bridgeData) != address(0x0), "You need to provide an actual bridge data contract.");
require(_ensAddress != address(0), "ENS cannot be the zero address.");
ens = ENS(_ensAddress);
require(_ensResolverAddress != address(0), "Resolver cannot be the zero address.");
resolver = ENSAddrResolverI(_ensResolverAddress);
rootNode = _rootNode;
}
modifier onlyBridgeControl()
{
require(msg.sender == bridgeData.getAddress("bridgeControl"), "bridgeControl key required for this function.");
_;
}
modifier onlyBridge()
{
require(msg.sender == bridgeData.getAddress("bridgeControl") || msg.sender == bridgeData.getAddress("bridgeHead") || msg.sender == bridgeData.getAddress("tokenHolder"),
"Only the bridge can execute this function.");
_;
}
modifier onlySubdomainControl()
{
require(msg.sender == bridgeData.getAddress("subdomainControl"), "subdomainControl key required for this function.");
_;
}
modifier onlyTokenAssignmentControl() {
require(msg.sender == bridgeData.getAddress("tokenAssignmentControl"), "tokenAssignmentControl key required for this function.");
_;
}
/*** Enable adjusting variables after deployment ***/
function setBridgeData(BridgeDataI _newBridgeData)
external
onlyBridgeControl
{
require(address(_newBridgeData) != address(0x0), "You need to provide an actual bridge data contract.");
emit BridgeDataChanged(address(bridgeData), address(_newBridgeData));
bridgeData = _newBridgeData;
}
function setDefaultResolver(address _newResolverAddress)
public
onlySubdomainControl
{
require(_newResolverAddress != address(0), "resolver cannot be the zero address.");
emit DefaultResolverChanged(address(resolver), _newResolverAddress);
resolver = ENSAddrResolverI(_newResolverAddress);
}
/*** Function that createControl has to call on Collections and that we want to be accessible ***/
function transferCreateControl(address _newCreateControl)
public
onlyBridgeControl
{
CollectionsL1CreateI(bridgeData.getAddress("Collections")).transferCreateControl(_newCreateControl);
}
/*** Functions needed for Creating Collections ***/
// Create a collection - this omits the subdomain registrar as we are that one ourselves.
function createCollectionFor(address payable _newOwner,
address _notificationContract,
string memory _ensName,
string memory _ensSubdomainName,
address _ensReverseRegistrarAddress)
public
onlyBridge
{
createInProgress = true;
CollectionsL1CreateI(bridgeData.getAddress("Collections")).createFor(_newOwner, _notificationContract, _ensName, _ensSubdomainName, address(this), _ensReverseRegistrarAddress);
createInProgress = false;
}
/*** Functions for ENS Registration ***/
// Call this with the label of the subnode, which is keccak256(bytes(_name)),
// and the target address it should point to (owner of the subnode).
function registerAddr(bytes32 _label, address _target)
external override
{
require(createInProgress || msg.sender == bridgeData.getAddress("subdomainControl"), "Addresses can only be registered with a Collection creation.");
bytes32 node = keccak256(abi.encodePacked(rootNode, _label));
address currentOwner = ens.owner(node);
require(currentOwner == address(0) || currentOwner == msg.sender, "Already registered, but not to caller.");
emit Registered(_label, node, _target);
ens.setSubnodeOwner(rootNode, _label, address(this));
ens.setResolver(node, address(resolver));
resolver.setAddr(node, _target);
}
// The subdomain controller can revert a name to unregistered.
function unregister(bytes32 _label)
external
onlySubdomainControl
{
bytes32 node = keccak256(abi.encodePacked(rootNode, _label));
address currentOwner = ens.owner(node);
require(currentOwner == address(this), "Not registered.");
emit Unregistered(_label, node);
resolver.setAddr(node, address(0));
ens.setSubnodeOwner(rootNode, _label, address(0));
}
// The subdomain controller can block a name so nobody can actually use it.
// This is done by registering the name but not having it point to a target address.
function blockRegistration(bytes32 _label)
external
onlySubdomainControl
{
bytes32 node = keccak256(abi.encodePacked(rootNode, _label));
address currentOwner = ens.owner(node);
emit Blocked(_label, node);
if (currentOwner != address(this)) {
// Make sure the name is registered to this contract.
ens.setSubnodeOwner(rootNode, _label, address(this));
}
// If a resolver is set, make sure the name does not point to any actual target.
// Otherwise, we don't even need a resolver set.
address existingResolverAddress = ens.resolver(node);
if (existingResolverAddress != address(0)) {
ENSAddrResolverI(existingResolverAddress).setAddr(node, address(0));
}
}
/*** Enable reverse ENS registration ***/
// Call this with the address of the reverse registrar for the respective network and the ENS name to register.
// The reverse registrar can be found as the owner of 'addr.reverse' in the ENS system.
// For Mainnet, the address needed is 0x9062c0a6dbd6108336bcbe4593a3d1ce05512069
function registerReverseENS(address _reverseRegistrarAddress, string calldata _name)
external
onlyTokenAssignmentControl
{
require(_reverseRegistrarAddress != address(0), "need a valid reverse registrar");
ENSReverseRegistrarI(_reverseRegistrarAddress).setName(_name);
}
/*** Make sure currency or NFT doesn't get stranded in this contract ***/
// If this contract gets a balance in some ERC20 contract after it's finished, then we can rescue it.
function rescueToken(IERC20 _foreignToken, address _to)
external
onlyTokenAssignmentControl
{
_foreignToken.transfer(_to, _foreignToken.balanceOf(address(this)));
}
// If this contract gets a balance in some ERC721 contract after it's finished, then we can rescue it.
function approveNFTrescue(IERC721 _foreignNFT, address _to)
external
onlyTokenAssignmentControl
{
_foreignNFT.setApprovalForAll(_to, true);
}
} | The subdomain controller can block a name so nobody can actually use it. This is done by registering the name but not having it point to a target address. Make sure the name is registered to this contract. | function blockRegistration(bytes32 _label)
external
onlySubdomainControl
{
bytes32 node = keccak256(abi.encodePacked(rootNode, _label));
address currentOwner = ens.owner(node);
emit Blocked(_label, node);
if (currentOwner != address(this)) {
ens.setSubnodeOwner(rootNode, _label, address(this));
}
if (existingResolverAddress != address(0)) {
ENSAddrResolverI(existingResolverAddress).setAddr(node, address(0));
}
}
| 5,889,640 |
./partial_match/1/0x2F1d72761b120aA1a7A88b2B662F7E4C63F20C76/sources/@violetprotocol/erc721extendable/contracts/extensions/base/receiver/IOnReceiveLogic.sol | OnReceive interface for contract-receiver hooks/ | interface IOnReceiveLogic {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) external returns (bool);
pragma solidity ^0.8.4;
}
| 15,623,859 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./Context.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address public _owner;
/**
* @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, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_mint(_owner, initialSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
require(owner == _owner, "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 { }
} | 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");
require(owner == _owner, "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 262,376 |
pragma solidity ^0.4.24;
import "./InterfaceToken.sol";
/**
* @title SimpleArtistContract
*/
contract SimpleArtistContract {
using SafeMath for uint256;
event Purchased(address indexed _funder, uint256 indexed _tokenId, uint256 _blocksPurchased, uint256 _totalValue);
event PurchaseBlock(address indexed _funder, uint256 indexed _tokenId, bytes32 _blockhash, uint256 _block);
modifier onlyValidAmounts() {
require(msg.value >= 0);
// Min price
require(msg.value >= pricePerBlockInWei);
// max price
require(msg.value <= (pricePerBlockInWei * maxBlockPurchaseInOneGo));
_;
}
/**
* @dev Throws if called by any account other than the artist.
*/
modifier onlyArtist() {
require(msg.sender == artist);
_;
}
address public artist;
InterfaceToken public token;
uint256 public pricePerBlockInWei;
uint256 public maxBlockPurchaseInOneGo;
bool public onlyShowPurchased = false;
address public foundationAddress = 0xf43aE50C468c3D3Fa0C3dC3454E797317EF53078;
uint256 public foundationPercentage = 5; // 5% to foundation
mapping(uint256 => uint256) internal blocknumberToTokenId;
mapping(uint256 => uint256[]) internal tokenIdToPurchasedBlocknumbers;
uint256 public lastPurchasedBlock = 0;
constructor(InterfaceToken _token, uint256 _pricePerBlockInWei, uint256 _maxBlockPurchaseInOneGo, address _artist) public {
require(_artist != address(0));
artist = _artist;
token = _token;
pricePerBlockInWei = _pricePerBlockInWei;
maxBlockPurchaseInOneGo = _maxBlockPurchaseInOneGo;
// set to current block mined in
lastPurchasedBlock = block.number;
}
/**
* @dev allows payment direct to contract - if no token will store value on contract
*/
function() public payable {
if (token.hasTokens(msg.sender)) {
purchase(token.firstToken(msg.sender));
}
else {
// 4% to foundation
uint foundationShare = msg.value / 100 * foundationPercentage;
foundationAddress.transfer(foundationShare);
// artists sent the remaining value
uint artistTotal = msg.value - foundationShare;
artist.transfer(artistTotal);
}
}
/**
* @dev purchase blocks with your Token ID to be displayed for a specific amount of blocks
* @param _tokenId the InterfaceToken token ID
*/
function purchase(uint256 _tokenId) public payable onlyValidAmounts {
require(token.exists(_tokenId));
// determine how many blocks purchased
uint256 blocksToPurchased = msg.value / pricePerBlockInWei;
// Start purchase from next block the current block is being mined
uint256 nextBlockToPurchase = block.number + 1;
// If next block is behind the next block to purchase, set next block to the last block
if (nextBlockToPurchase < lastPurchasedBlock) {
// reducing wasted loops to find a viable block to purchase
nextBlockToPurchase = lastPurchasedBlock;
}
uint8 purchased = 0;
while (purchased < blocksToPurchased) {
if (tokenIdOf(nextBlockToPurchase) == 0) {
purchaseBlock(nextBlockToPurchase, _tokenId);
purchased++;
}
// move next block on to find another free space
nextBlockToPurchase = nextBlockToPurchase + 1;
}
// update last block once purchased
lastPurchasedBlock = nextBlockToPurchase;
// payments
// 4% to foundation
uint foundationShare = msg.value / 100 * foundationPercentage;
foundationAddress.transfer(foundationShare);
// artists sent the remaining value
uint artistTotal = msg.value - foundationShare;
artist.transfer(artistTotal);
emit Purchased(msg.sender, _tokenId, blocksToPurchased, msg.value);
}
function purchaseBlock(uint256 _blocknumber, uint256 _tokenId) internal {
// keep track of the token associated to the block
blocknumberToTokenId[_blocknumber] = _tokenId;
// Keep track of the blocks purchased by the token
tokenIdToPurchasedBlocknumbers[_tokenId].push(_blocknumber);
// Emit event for logging/tracking
emit PurchaseBlock(msg.sender, _tokenId, getPurchasedBlockhash(_blocknumber), _blocknumber);
}
/**
* @dev Attempts to work out the next block which will be funded
*/
function nextPurchasableBlocknumber() public view returns (uint256 _nextFundedBlock) {
if (block.number < lastPurchasedBlock) {
return lastPurchasedBlock;
}
return block.number + 1;
}
/**
* @dev Returns the blocks which the provided token has purchased
*/
function blocknumbersOf(uint256 _tokenId) public view returns (uint256[] _blocks) {
return tokenIdToPurchasedBlocknumbers[_tokenId];
}
/**
* @dev Return token ID for the provided block or 0 when not found
*/
function tokenIdOf(uint256 _blockNumber) public view returns (uint256 _tokenId) {
return blocknumberToTokenId[_blockNumber];
}
/**
* @dev Get the block hash the given block number
* @param _blocknumber the block to generate hash for
*/
function getPurchasedBlockhash(uint256 _blocknumber) public view returns (bytes32 _tokenHash) {
// Do not allow this to be called for hashes which aren't purchased
require(tokenIdOf(_blocknumber) != 0);
uint256 tokenId = tokenIdOf(_blocknumber);
return token.blockhashOf(tokenId);
}
/**
* @dev Generates default block hash behaviour - helps with tests
*/
function nativeBlockhash(uint256 _blocknumber) public view returns (bytes32 _tokenHash) {
return blockhash(_blocknumber);
}
/**
* @dev Generates a unique token hash for the token
* @return the hash and its associated block
*/
function nextHash() public view returns (bytes32 _tokenHash, uint256 _nextBlocknumber) {
uint256 nextBlocknumber = block.number - 1;
// if current block number has been allocated then use it
if (tokenIdOf(nextBlocknumber) != 0) {
return (getPurchasedBlockhash(nextBlocknumber), nextBlocknumber);
}
if (onlyShowPurchased) {
return (0x0, 0x0);
}
// if no one own the current blockhash return current
return (nativeBlockhash(nextBlocknumber), nextBlocknumber);
}
/**
* @dev Returns blocknumber - helps with tests
*/
function blocknumber() public view returns (uint256 _blockNumber) {
return block.number;
}
/**
* @dev Utility function for updating price per block
* @param _priceInWei the price in wei
*/
function setPricePerBlockInWei( uint256 _priceInWei) external onlyArtist {
pricePerBlockInWei = _priceInWei;
}
/**
* @dev Utility function for updating max blocks
* @param _maxBlockPurchaseInOneGo max blocks per purchase
*/
function setMaxBlockPurchaseInOneGo( uint256 _maxBlockPurchaseInOneGo) external onlyArtist {
maxBlockPurchaseInOneGo = _maxBlockPurchaseInOneGo;
}
/**
* @dev Utility function for only show purchased
* @param _onlyShowPurchased flag for only showing purchased hashes
*/
function setOnlyShowPurchased(bool _onlyShowPurchased) external onlyArtist {
onlyShowPurchased = _onlyShowPurchased;
}
}
| Utility function for updating max blocks _maxBlockPurchaseInOneGo max blocks per purchase/ | function setMaxBlockPurchaseInOneGo( uint256 _maxBlockPurchaseInOneGo) external onlyArtist {
maxBlockPurchaseInOneGo = _maxBlockPurchaseInOneGo;
}
| 12,627,211 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"ERC1155: balance query for the zero address"
);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
"ERC1155: accounts and ids length mismatch"
);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
_msgSender() != operator,
"ERC1155: setting approval status for self"
);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
account,
id,
amount,
data
);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
address(0),
to,
ids,
amounts,
data
);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
""
);
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"ERC1155: burn amount exceeds balance"
);
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"ERC1155: burn amount exceeds balance"
);
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver(to).onERC1155Received.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response !=
IERC1155Receiver(to).onERC1155BatchReceived.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// Copyright (c) 2018 Tasuku Nakamura
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
///@author Zapper
///@notice This contract checks if a message has been signed by a verified signer via personal_sign.
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
contract SignatureVerifier_V2 {
address public signer;
constructor(address _signer) {
signer = _signer;
}
function verify(bytes32 messageHash, bytes memory signature)
internal
view
returns (bool)
{
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}
function getEthSignedMessageHash(bytes32 messageHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
messageHash
)
);
}
function recoverSigner(
bytes32 _ethSignedMessageHash,
bytes memory _signature
) internal pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory signature)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(signature.length == 65, "invalid signature length");
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
///@author Zapper
///@notice This contract manages Zapper V2 NFTs and Volts.
/// Volts can be claimed through quests in order to mint various NFTs.
/// Crafting combines NFTs of the same type into higher tier NFTs. NFTs
/// can also be redemeed for Volts.
// SPDX-License-Identifier: GPL-2.0
pragma solidity ^0.8.0;
import "./ERC1155/ERC1155.sol";
import "./access/Ownable.sol";
import "./SignatureVerifier/SignatureVerifier_V2.sol";
import "./ERC1155/IERC1155.sol";
import "./utils/Strings.sol";
contract Zapper_NFT_V2_0_1 is ERC1155, Ownable, SignatureVerifier_V2 {
// Used in pausable modifier
bool public paused;
// NFT name
string public name;
// NFT symbol
string public symbol;
// Season deadline
uint256 public deadline;
// Modifier to apply to cost of NFT when redeeming in bps
uint256 public redeemModifier = 7500;
// Quantity of NFTs consumed per crafting event
uint256 public craftingRequirement = 3;
// Mapping from token ID to token supply
mapping(uint256 => uint256) private tokenSupply;
// Mapping of accessory contracts that have permission to mint
mapping(address => bool) public accessoryContract;
// Total Volt supply
uint256 public voltSupply;
// Mapping from account to Volt balance
mapping(address => uint256) public voltBalance;
// Mapping from token ID to token existence
mapping(uint256 => bool) private exists;
// Mapping for the rarity classes for use in crafting
mapping(uint256 => uint256) public nextRarity;
// Mapping from token ID to token cost in volts
mapping(uint256 => uint256) public cost;
// Mapping from account to nonce
mapping(address => uint256) public nonces;
// Emitted when `account` claims Volts
event ClaimVolts(
address indexed account,
uint256 voltsRecieved,
uint256 nonce
);
// Emitted when `account` burns Volts
event BurnVolts(address indexed account, uint256 voltsBurned);
// Emitted when `account` mints one or more NFTs by spending Volts
event Mint(address indexed account, uint256 voltsSpent);
// Emitted when `account` redeems Volts by burning one or more NFTs
event Redeem(address indexed account, uint256 voltsRecieved);
// Emitted when `account` crafts one or more of the same NFT
event Craft(address indexed account, uint256 craftID);
// Emitted when `account` crafts multiple different NFTs
event CraftBatch(address indexed account, uint256[] craftIDs);
// Emitted when a new NFT type is added
event Add(uint256 id, uint256 cost, uint256 nextRarity);
// Emitted when the baseURI is updated
event updateBaseURI(string uri);
modifier pausable {
require(!paused, "Paused");
_;
}
modifier beforeDeadline {
require(block.timestamp <= deadline, "Deadline elapsed");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
address signer,
address manager,
uint256 _deadline
) ERC1155(_uri) SignatureVerifier_V2(signer) {
name = _name;
symbol = _symbol;
deadline = _deadline;
transferOwnership(manager);
}
/**
* @dev Adds a new NFT and initializes crafting params
* @param costs An array of the cost of each ID. 0 if it cannot
* be crafted
* @param nextRarities An array of higher rarity IDs which can be
* crafted from the ID. 0 if max rarity.
*/
function add(
uint256[] calldata ids,
uint256[] calldata costs,
uint256[] calldata nextRarities
) external onlyOwner {
require(
ids.length == costs.length && ids.length == nextRarities.length,
"Mismatched array lengths"
);
for (uint256 i = 0; i < ids.length; i++) {
uint256 newId = ids[i];
require(!exists[newId], "ID already exists");
require(newId != 0, "Invalid ID");
exists[newId] = true;
cost[newId] = costs[i];
nextRarity[newId] = nextRarities[i];
emit Add(newId, costs[i], nextRarities[i]);
}
}
/**
* @notice Claims Volts earned through quests
* @param voltsEarned The quantity of Volts being awarded
* @param signature The signature granting msg.sender the volts
*/
function claimVolts(uint256 voltsEarned, bytes calldata signature)
external
pausable
beforeDeadline
{
bytes32 messageHash =
getMessageHash(msg.sender, voltsEarned, nonces[msg.sender]++);
require(verify(messageHash, signature), "Invalid Signature");
_createVolts(voltsEarned);
emit ClaimVolts(msg.sender, voltsEarned, nonces[msg.sender]);
}
/**
* @notice Burns Volts
* @param voltsBurned The quantity of Volts being burned
*/
function burnVolts(uint256 voltsBurned) external pausable {
_burnVolts(voltsBurned);
emit BurnVolts(msg.sender, voltsBurned);
}
/**
* @notice Mints a desired quantity of a single NFT ID
* in exchange for Volts
* @param id The ID of the NFT to mint
* @param quantity The quantity of the NFT to mint
*/
function mint(uint256 id, uint256 quantity) external pausable {
require(exists[id], "Invalid ID");
uint256 voltsSpent;
if (!accessoryContract[msg.sender]) {
require(cost[id] > 0, "Price not set");
voltsSpent = cost[id] * quantity;
_burnVolts(voltsSpent);
}
_mint(msg.sender, id, quantity, new bytes(0));
emit Mint(msg.sender, voltsSpent);
}
/**
* @notice Batch Mints desired quantities of different NFT IDs
* in exchange for Volts
* @param ids An array consisting of the IDs of the NFTs to mint
* @param quantities An array consisting of the quantities of the NFTs to mint
*/
function mintBatch(uint256[] calldata ids, uint256[] calldata quantities)
external
pausable
{
require(ids.length == quantities.length, "Mismatched array lengths");
uint256 voltsSpent;
if (!accessoryContract[msg.sender]) {
for (uint256 i = 0; i < ids.length; i++) {
require(exists[ids[i]], "Invalid ID");
require(cost[ids[i]] > 0, "Price not set");
voltsSpent += cost[ids[i]] * quantities[i];
}
_burnVolts(voltsSpent);
} else {
for (uint256 i = 0; i < ids.length; i++) {
require(exists[ids[i]], "Invalid ID");
}
}
_mintBatch(msg.sender, ids, quantities, new bytes(0));
emit Mint(msg.sender, voltsSpent);
}
/**
* @notice Burns an NFT
* @dev Does not award Volts!
* @param id The ID of the NFT to burn
* @param quantity The quantity of the NFT to burn
*/
function burn(uint256 id, uint256 quantity) external pausable {
_burn(msg.sender, id, quantity);
}
/**
* @notice Batch burns NFTs
* @dev Does not award Volts!
* @param ids An array consisting of the IDs of the NFTs to burn
* @param quantities An array consisting of the quantities
* of each NFT to burn
*/
function burnBatch(uint256[] calldata ids, uint256[] calldata quantities)
external
pausable
{
_burnBatch(msg.sender, ids, quantities);
}
/**
* @notice Redeems an NFT for Volts. Redeeming NFTs is
* subject to a modifier which returns some percentage of
* the full cost of the NFT
* @param id ID of the NFT to redeem
* @param quantity The quantity of the NFT being redeemed
*/
function redeem(uint256 id, uint256 quantity) external pausable {
require(cost[id] > 0, "Cannot redeem this type");
_burn(msg.sender, id, quantity);
uint256 voltsRecieved = (cost[id] * quantity * redeemModifier) / 10000;
_createVolts(voltsRecieved);
emit Redeem(msg.sender, voltsRecieved);
}
/**
* @notice Redeems multiple NFTs for Volts. Redeeming NFTs is
* subject to a modifier which returns some percentage of
* the full cost of the NFT
* @param ids An array consisting of the IDs of the NFTs to redeem
* @param quantities An array consisting of the quantities of
* each NFT to redeem
*/
function redeemBatch(uint256[] calldata ids, uint256[] calldata quantities)
external
pausable
{
_burnBatch(msg.sender, ids, quantities);
uint256 voltsRecieved;
for (uint256 i = 0; i < ids.length; i++) {
require(cost[ids[i]] > 0, "Cannot redeem this type");
voltsRecieved +=
(cost[ids[i]] * quantities[i] * redeemModifier) /
10000;
}
_createVolts(voltsRecieved);
emit Redeem(msg.sender, voltsRecieved);
}
/**
* @notice Crafts higher tier NFTs with lower tier NFTs
* @param id ID of the NFT used for crafting
* @param quantity The quantity of id to consume in crafting
*/
function craft(uint256 id, uint256 quantity) external pausable {
uint256 craftID = nextRarity[id];
require(craftID != 0, "Already maximum rarity");
require(
quantity % craftingRequirement == 0,
"Incorrect quantity for crafting"
);
_burn(msg.sender, id, quantity);
uint256 craftQuantity = quantity / craftingRequirement;
_mint(msg.sender, craftID, craftQuantity, new bytes(0));
emit Craft(msg.sender, craftID);
}
/**
* @notice Crafts multiple different higher tier NFTs with
* lower tier NFTs
* @param ids An array consisting of the IDs of the NFT used for crafting
* @param quantities An array consisting of the quantities of the NFT
* to consume in crafting
*/
function craftBatch(uint256[] calldata ids, uint256[] calldata quantities)
external
pausable
{
_burnBatch(msg.sender, ids, quantities);
uint256[] memory craftQuantities = new uint256[](quantities.length);
uint256[] memory craftIds = new uint256[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 craftID = nextRarity[ids[i]];
require(craftID != 0, "Already maximum rarity");
require(
quantities[i] % craftingRequirement == 0,
"Incorrect quantity for crafting"
);
craftIds[i] = craftID;
craftQuantities[i] = quantities[i] / craftingRequirement;
}
_mintBatch(msg.sender, craftIds, craftQuantities, new bytes(0));
emit CraftBatch(msg.sender, craftIds);
}
/**
* @dev Function to set the URI for all NFT IDs
*/
function setBaseURI(string calldata _uri) external onlyOwner {
_setURI(_uri);
emit updateBaseURI(_uri);
}
/**
* @dev Returns the URI of a token given its ID
* @param id ID of the token to query
* @return uri of the token or an empty string if it does not exist
*/
function uri(uint256 id) public view override returns (string memory) {
require(exists[id], "URI query for nonexistent token");
string memory baseUri = super.uri(0);
return string(abi.encodePacked(baseUri, Strings.toString(id)));
}
/**
* @notice Maps the rarity classes and Volt costs
* for use in crafting
* @param ids An array of the IDs being updated
* @param costs An array of the cost of each ID
* @param nextRarities An array of higher rarity IDs which
* can be crafted from the ID
*/
function updateCraftingParameters(
uint256[] calldata ids,
uint256[] calldata costs,
uint256[] calldata nextRarities
) external onlyOwner {
require(
ids.length == costs.length && ids.length == nextRarities.length,
"Mismatched array lengths"
);
for (uint256 i = 0; i < ids.length; i++) {
require(exists[ids[i]], "ID does not exist");
cost[ids[i]] = costs[i];
nextRarity[ids[i]] = nextRarities[i];
}
}
/**
* @dev Updates the modifier which is used when redeeming
* NFTs for Volts
*/
function updateRedeemModifier(uint256 _redeemModifier) external onlyOwner {
redeemModifier = _redeemModifier;
}
/**
* @dev Updates the crafting requirement modifier which determines
* the quantity of NFTs that are burned in order to craft
* higher rarity NFTs
*/
function updateCraftingRequirement(uint256 _craftingRequirement)
external
onlyOwner
{
craftingRequirement = _craftingRequirement;
}
/**
* @dev Updates the mapping of accessory contracts which have
* special permssions to mint NFTs (lootbox, bridge, etc.)
*/
function updateAccessoryContracts(address _accessoryContract, bool allowed)
external
onlyOwner
{
accessoryContract[_accessoryContract] = allowed;
}
/**
* @dev Updates the deadline after which Volts can no longer be claimed
*/
function updateDeadline(uint256 _deadline) external onlyOwner {
deadline = _deadline;
}
/**
* @dev Returns the total quantity for a token ID
* @param id ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 id) external view returns (uint256) {
return tokenSupply[id];
}
/**
* @dev Pause or unpause the contract
*/
function pause() external onlyOwner {
paused = !paused;
}
/**
* @dev Function to return the message hash that will be
* signed by the signer
*/
function getMessageHash(
address account,
uint256 volts,
uint256 nonce
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(account, volts, nonce));
}
/**
* @dev Internal override function for minting an NFT
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal override {
super._mint(account, id, amount, data);
tokenSupply[id] += amount;
}
/**
* @dev Internal override function for batch minting NFTs
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
tokenSupply[ids[i]] += amounts[i];
}
}
/**
* @dev Internal override function for burning an NFT
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal override {
super._burn(account, id, amount);
tokenSupply[id] -= amount;
}
/**
* @dev Internal override function for batch burning NFTs
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal override {
super._burnBatch(account, ids, amounts);
for (uint256 i; i < ids.length; i++) {
tokenSupply[ids[i]] -= amounts[i];
}
}
/**
* @dev Internal function to create volts
*/
function _createVolts(uint256 quantity) internal {
voltBalance[msg.sender] += quantity;
voltSupply += quantity;
}
/**
* @dev Internal function to burn volts
*/
function _burnVolts(uint256 quantity) internal {
require(
voltBalance[msg.sender] >= quantity,
"Insufficient Volt balance"
);
voltBalance[msg.sender] -= quantity;
voltSupply -= quantity;
}
}
// 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 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 String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| Returns the URI of a token given its ID id ID of the token to query return uri of the token or an empty string if it does not exist/ | function uri(uint256 id) public view override returns (string memory) {
require(exists[id], "URI query for nonexistent token");
string memory baseUri = super.uri(0);
return string(abi.encodePacked(baseUri, Strings.toString(id)));
}
| 1,217,835 |
pragma solidity 0.5.12;
pragma experimental ABIEncoderV2;
contract Token {
uint256 public totalSupply;
function BALANCEOF126(address _owner) view public returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER539(address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM134(address _from, address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function APPROVE766(address _spender, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE680(address _owner, address _spender) public view returns (uint256 remaining); //inject NONSTANDARD NAMING
event TRANSFER377(address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event APPROVAL896(address _owner, address _spender, uint256 _value); //inject NONSTANDARD NAMING
}
contract ERC20Token is Token {
function TRANSFER539(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit TRANSFER377(msg.sender, _to, _value);
return true;
} else { return false; }
}
function TRANSFERFROM134(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit TRANSFER377(_from, _to, _value);
return true;
} else { return false; }
}
function BALANCEOF126(address _owner) view public returns (uint256 balance) { //inject NONSTANDARD NAMING
return balances[_owner];
}
function APPROVE766(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL896(msg.sender, _spender, _value);
return true;
}
function ALLOWANCE680(address _owner, address _spender) view public returns (uint256 remaining) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
library SafeMath {
function MUL746(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
// 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;
}
function DIV871(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function SUB288(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD535(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
assert(c >= a);
return c;
}
}
library AddressUtils {
function ISCONTRACT297(address addr) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
interface ERC165 {
function SUPPORTSINTERFACE396(bytes4 _interfaceId) //inject NONSTANDARD NAMING
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant interfaceid_erc165197 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_REGISTERINTERFACE866(interfaceid_erc165197);
}
function SUPPORTSINTERFACE396(bytes4 _interfaceId) //inject NONSTANDARD NAMING
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _REGISTERINTERFACE866(bytes4 _interfaceId) //inject NONSTANDARD NAMING
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC721Receiver {
bytes4 internal constant erc721_received613 = 0xf0b9e5ba; //inject NONSTANDARD NAMING
function ONERC721RECEIVED739( //inject NONSTANDARD NAMING
address _from,
uint256 _tokenId,
bytes memory _data
)
public
returns(bytes4);
}
contract ERC721Basic is ERC165 {
event TRANSFER377( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
);
event APPROVAL896( //inject NONSTANDARD NAMING
address _owner,
address _approved,
uint256 _tokenId
);
event APPROVALFORALL957( //inject NONSTANDARD NAMING
address _owner,
address _operator,
bool _approved
);
function BALANCEOF126(address _owner) public view returns (uint256 _balance); //inject NONSTANDARD NAMING
function OWNEROF291(uint256 _tokenId) public view returns (address _owner); //inject NONSTANDARD NAMING
function EXISTS362(uint256 _tokenId) public view returns (bool _exists); //inject NONSTANDARD NAMING
function APPROVE766(address _to, uint256 _tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED462(uint256 _tokenId) //inject NONSTANDARD NAMING
public view returns (address _operator);
function SETAPPROVALFORALL90(address _operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL509(address _owner, address _operator) //inject NONSTANDARD NAMING
public view returns (bool);
function TRANSFERFROM134(address _from, address _to, uint256 _tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM921(address _from, address _to, uint256 _tokenId) //inject NONSTANDARD NAMING
public;
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
public;
}
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant interfaceid_erc721619 = 0x80ac58cd; //inject NONSTANDARD NAMING
bytes4 private constant interfaceid_erc721exists608 = 0x4f558e79; //inject NONSTANDARD NAMING
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant erc721_received613 = 0xf0b9e5ba; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
uint public testint;
modifier ONLYOWNEROF128(uint256 _tokenId) { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == msg.sender);
_;
}
modifier CANTRANSFER884(uint256 _tokenId) { //inject NONSTANDARD NAMING
require(ISAPPROVEDOROWNER880(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE866(interfaceid_erc721619);
_REGISTERINTERFACE866(interfaceid_erc721exists608);
}
function BALANCEOF126(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function OWNEROF291(uint256 _tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function EXISTS362(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function APPROVE766(address _to, uint256 _tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF291(_tokenId);
require(_to != owner);
require(msg.sender == owner || ISAPPROVEDFORALL509(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit APPROVAL896(owner, _to, _tokenId);
}
function GETAPPROVED462(uint256 _tokenId) public view returns (address) { //inject NONSTANDARD NAMING
return tokenApprovals[_tokenId];
}
function SETAPPROVALFORALL90(address _to, bool _approved) public { //inject NONSTANDARD NAMING
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit APPROVALFORALL957(msg.sender, _to, _approved);
}
function ISAPPROVEDFORALL509( //inject NONSTANDARD NAMING
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
function TRANSFERFROM134( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
)
public
CANTRANSFER884(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
CLEARAPPROVAL440(_from, _tokenId);
REMOVETOKENFROM320(_from, _tokenId);
ADDTOKENTO890(_to, _tokenId);
emit TRANSFER377(_from, _to, _tokenId);
}
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId
)
public
CANTRANSFER884(_tokenId)
{
// solium-disable-next-line arg-overflow
SAFETRANSFERFROM921(_from, _to, _tokenId, "");
}
function SAFETRANSFERFROM921( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
public
CANTRANSFER884(_tokenId)
{
TRANSFERFROM134(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(CHECKANDCALLSAFETRANSFER327(_from, _to, _tokenId, _data));
}
function ISAPPROVEDOROWNER880( //inject NONSTANDARD NAMING
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = OWNEROF291(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
GETAPPROVED462(_tokenId) == _spender ||
ISAPPROVEDFORALL509(owner, _spender)
);
}
function _MINT613(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(_to != address(0));
ADDTOKENTO890(_to, _tokenId);
emit TRANSFER377(address(0), _to, _tokenId);
}
function _BURN402(address _owner, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
CLEARAPPROVAL440(_owner, _tokenId);
REMOVETOKENFROM320(_owner, _tokenId);
emit TRANSFER377(_owner, address(0), _tokenId);
}
function CLEARAPPROVAL440(address _owner, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
function ADDTOKENTO890(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].ADD535(1);
}
function REMOVETOKENFROM320(address _from, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF291(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].SUB288(1);
tokenOwner[_tokenId] = address(0);
}
function CHECKANDCALLSAFETRANSFER327( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!_to.ISCONTRACT297()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).ONERC721RECEIVED739(
_from, _tokenId, _data);
return (retval == erc721_received613);
}
}
contract ERC721BasicTokenMock is ERC721BasicToken {
function MINT436(address _to, uint256 _tokenId) public { //inject NONSTANDARD NAMING
super._MINT613(_to, _tokenId);
}
function BURN214(uint256 _tokenId) public { //inject NONSTANDARD NAMING
super._BURN402(OWNEROF291(_tokenId), _tokenId);
}
}
contract StandardBounties {
using SafeMath for uint256;
struct Bounty {
address payable[] issuers; // An array of individuals who have complete control over the bounty, and can edit any of its parameters
address[] approvers; // An array of individuals who are allowed to accept the fulfillments for a particular bounty
uint deadline; // The Unix timestamp before which all submissions must be made, and after which refunds may be processed
address token; // The address of the token associated with the bounty (should be disregarded if the tokenVersion is 0)
uint tokenVersion; // The version of the token being used for the bounty (0 for ETH, 20 for ERC20, 721 for ERC721)
uint balance; // The number of tokens which the bounty is able to pay out or refund
bool hasPaidOut; // A boolean storing whether or not the bounty has paid out at least once, meaning refunds are no longer allowed
Fulfillment[] fulfillments; // An array of Fulfillments which store the various submissions which have been made to the bounty
Contribution[] contributions; // An array of Contributions which store the contributions which have been made to the bounty
}
struct Fulfillment {
address payable[] fulfillers; // An array of addresses who should receive payouts for a given submission
address submitter; // The address of the individual who submitted the fulfillment, who is able to update the submission as needed
}
struct Contribution {
address payable contributor; // The address of the individual who contributed
uint amount; // The amount of tokens the user contributed
bool refunded; // A boolean storing whether or not the contribution has been refunded yet
}
uint public numBounties; // An integer storing the total number of bounties in the contract
mapping(uint => Bounty) public bounties; // A mapping of bountyIDs to bounties
mapping (uint => mapping (uint => bool)) public tokenBalances; // A mapping of bountyIds to tokenIds to booleans, storing whether a given bounty has a given ERC721 token in its balance
address public owner; // The address of the individual who's allowed to set the metaTxRelayer address
address public metaTxRelayer; // The address of the meta transaction relayer whose _sender is automatically trusted for all contract calls
bool public callStarted; // Ensures mutex for the entire contract
modifier CALLNOTSTARTED963(){ //inject NONSTANDARD NAMING
require(!callStarted);
callStarted = true;
_;
callStarted = false;
}
modifier VALIDATEBOUNTYARRAYINDEX962( //inject NONSTANDARD NAMING
uint _index)
{
require(_index < numBounties);
_;
}
modifier VALIDATECONTRIBUTIONARRAYINDEX279( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].contributions.length);
_;
}
modifier VALIDATEFULFILLMENTARRAYINDEX396( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].fulfillments.length);
_;
}
modifier VALIDATEISSUERARRAYINDEX737( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].issuers.length);
_;
}
modifier VALIDATEAPPROVERARRAYINDEX32( //inject NONSTANDARD NAMING
uint _bountyId,
uint _index)
{
require(_index < bounties[_bountyId].approvers.length);
_;
}
modifier ONLYISSUER653( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId)
{
require(_sender == bounties[_bountyId].issuers[_issuerId]);
_;
}
modifier ONLYSUBMITTER83( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId)
{
require(_sender ==
bounties[_bountyId].fulfillments[_fulfillmentId].submitter);
_;
}
modifier ONLYCONTRIBUTOR9( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _contributionId)
{
require(_sender ==
bounties[_bountyId].contributions[_contributionId].contributor);
_;
}
modifier ISAPPROVER33( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _approverId)
{
require(_sender == bounties[_bountyId].approvers[_approverId]);
_;
}
modifier HASNOTPAID405( //inject NONSTANDARD NAMING
uint _bountyId)
{
require(!bounties[_bountyId].hasPaidOut);
_;
}
modifier HASNOTREFUNDED93( //inject NONSTANDARD NAMING
uint _bountyId,
uint _contributionId)
{
require(!bounties[_bountyId].contributions[_contributionId].refunded);
_;
}
modifier SENDERISVALID782( //inject NONSTANDARD NAMING
address _sender)
{
require(msg.sender == _sender || msg.sender == metaTxRelayer);
_;
}
constructor() public {
// The owner of the contract is automatically designated to be the deployer of the contract
owner = msg.sender;
}
function SETMETATXRELAYER306(address _relayer) //inject NONSTANDARD NAMING
external
{
require(msg.sender == owner); // Checks that only the owner can call
require(metaTxRelayer == address(0)); // Ensures the meta tx relayer can only be set once
metaTxRelayer = _relayer;
}
function ISSUEBOUNTY607( //inject NONSTANDARD NAMING
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion)
public
SENDERISVALID782(_sender)
returns (uint)
{
require(_tokenVersion == 0 || _tokenVersion == 20 || _tokenVersion == 721); // Ensures a bounty can only be issued with a valid token version
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
uint bountyId = numBounties; // The next bounty's index will always equal the number of existing bounties
Bounty storage newBounty = bounties[bountyId];
newBounty.issuers = _issuers;
newBounty.approvers = _approvers;
newBounty.deadline = _deadline;
newBounty.tokenVersion = _tokenVersion;
if (_tokenVersion != 0){
newBounty.token = _token;
}
numBounties = numBounties.ADD535(1); // Increments the number of bounties, since a new one has just been added
emit BOUNTYISSUED291(bountyId,
_sender,
_issuers,
_approvers,
_data, // Instead of storing the string on-chain, it is emitted within the event for easy off-chain consumption
_deadline,
_token,
_tokenVersion);
return (bountyId);
}
function ISSUEANDCONTRIBUTE529( //inject NONSTANDARD NAMING
address payable _sender,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _depositAmount)
public
payable
returns(uint)
{
uint bountyId = ISSUEBOUNTY607(_sender, _issuers, _approvers, _data, _deadline, _token, _tokenVersion);
CONTRIBUTE618(_sender, bountyId, _depositAmount);
return (bountyId);
}
function CONTRIBUTE618( //inject NONSTANDARD NAMING
address payable _sender,
uint _bountyId,
uint _amount)
public
payable
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
CALLNOTSTARTED963
{
require(_amount > 0); // Contributions of 0 tokens or token ID 0 should fail
bounties[_bountyId].contributions.push(
Contribution(_sender, _amount, false)); // Adds the contribution to the bounty
if (bounties[_bountyId].tokenVersion == 0){
bounties[_bountyId].balance = bounties[_bountyId].balance.ADD535(_amount); // Increments the balance of the bounty
require(msg.value == _amount);
} else if (bounties[_bountyId].tokenVersion == 20){
bounties[_bountyId].balance = bounties[_bountyId].balance.ADD535(_amount); // Increments the balance of the bounty
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
require(ERC20Token(bounties[_bountyId].token).TRANSFERFROM134(_sender,
address(this),
_amount));
} else if (bounties[_bountyId].tokenVersion == 721){
tokenBalances[_bountyId][_amount] = true; // Adds the 721 token to the balance of the bounty
require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds
ERC721BasicToken(bounties[_bountyId].token).TRANSFERFROM134(_sender,
address(this),
_amount);
} else {
revert();
}
emit CONTRIBUTIONADDED888(_bountyId,
bounties[_bountyId].contributions.length - 1, // The new contributionId
_sender,
_amount);
}
function REFUNDCONTRIBUTION719( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _contributionId)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATECONTRIBUTIONARRAYINDEX279(_bountyId, _contributionId)
ONLYCONTRIBUTOR9(_sender, _bountyId, _contributionId)
HASNOTPAID405(_bountyId)
HASNOTREFUNDED93(_bountyId, _contributionId)
CALLNOTSTARTED963
{
require(now > bounties[_bountyId].deadline); // Refunds may only be processed after the deadline has elapsed
Contribution storage contribution = bounties[_bountyId].contributions[_contributionId];
contribution.refunded = true;
TRANSFERTOKENS903(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
emit CONTRIBUTIONREFUNDED423(_bountyId, _contributionId);
}
function REFUNDMYCONTRIBUTIONS1000( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint[] memory _contributionIds)
public
SENDERISVALID782(_sender)
{
for (uint i = 0; i < _contributionIds.length; i++){
REFUNDCONTRIBUTION719(_sender, _bountyId, _contributionIds[i]);
}
}
function REFUNDCONTRIBUTIONS786( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint[] memory _contributionIds)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
CALLNOTSTARTED963
{
for (uint i = 0; i < _contributionIds.length; i++){
require(_contributionIds[i] < bounties[_bountyId].contributions.length);
Contribution storage contribution = bounties[_bountyId].contributions[_contributionIds[i]];
require(!contribution.refunded);
contribution.refunded = true;
TRANSFERTOKENS903(_bountyId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor
}
emit CONTRIBUTIONSREFUNDED218(_bountyId, _sender, _contributionIds);
}
function DRAINBOUNTY345( //inject NONSTANDARD NAMING
address payable _sender,
uint _bountyId,
uint _issuerId,
uint[] memory _amounts)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
CALLNOTSTARTED963
{
if (bounties[_bountyId].tokenVersion == 0 || bounties[_bountyId].tokenVersion == 20){
require(_amounts.length == 1); // ensures there's only 1 amount of tokens to be returned
require(_amounts[0] <= bounties[_bountyId].balance); // ensures an issuer doesn't try to drain the bounty of more tokens than their balance permits
TRANSFERTOKENS903(_bountyId, _sender, _amounts[0]); // Performs the draining of tokens to the issuer
} else {
for (uint i = 0; i < _amounts.length; i++){
require(tokenBalances[_bountyId][_amounts[i]]);// ensures an issuer doesn't try to drain the bounty of a token it doesn't have in its balance
TRANSFERTOKENS903(_bountyId, _sender, _amounts[i]);
}
}
emit BOUNTYDRAINED424(_bountyId, _sender, _amounts);
}
function PERFORMACTION966( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
{
emit ACTIONPERFORMED922(_bountyId, _sender, _data); // The _data string is emitted in an event for easy off-chain consumption
}
function FULFILLBOUNTY596( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
{
require(now < bounties[_bountyId].deadline); // Submissions are only allowed to be made before the deadline
require(_fulfillers.length > 0); // Submissions with no fulfillers would mean no one gets paid out
bounties[_bountyId].fulfillments.push(Fulfillment(_fulfillers, _sender));
emit BOUNTYFULFILLED198(_bountyId,
(bounties[_bountyId].fulfillments.length - 1),
_fulfillers,
_data, // The _data string is emitted in an event for easy off-chain consumption
_sender);
}
function UPDATEFULFILLMENT168( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId,
address payable[] memory _fulfillers,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEFULFILLMENTARRAYINDEX396(_bountyId, _fulfillmentId)
ONLYSUBMITTER83(_sender, _bountyId, _fulfillmentId) // Only the original submitter of a fulfillment may update their submission
{
bounties[_bountyId].fulfillments[_fulfillmentId].fulfillers = _fulfillers;
emit FULFILLMENTUPDATED42(_bountyId,
_fulfillmentId,
_fulfillers,
_data); // The _data string is emitted in an event for easy off-chain consumption
}
function ACCEPTFULFILLMENT330( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _fulfillmentId,
uint _approverId,
uint[] memory _tokenAmounts)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEFULFILLMENTARRAYINDEX396(_bountyId, _fulfillmentId)
ISAPPROVER33(_sender, _bountyId, _approverId)
CALLNOTSTARTED963
{
// now that the bounty has paid out at least once, refunds are no longer possible
bounties[_bountyId].hasPaidOut = true;
Fulfillment storage fulfillment = bounties[_bountyId].fulfillments[_fulfillmentId];
require(_tokenAmounts.length == fulfillment.fulfillers.length); // Each fulfiller should get paid some amount of tokens (this can be 0)
for (uint256 i = 0; i < fulfillment.fulfillers.length; i++){
if (_tokenAmounts[i] > 0){
// for each fulfiller associated with the submission
TRANSFERTOKENS903(_bountyId, fulfillment.fulfillers[i], _tokenAmounts[i]);
}
}
emit FULFILLMENTACCEPTED617(_bountyId,
_fulfillmentId,
_sender,
_tokenAmounts);
}
function FULFILLANDACCEPT822( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint _approverId,
uint[] memory _tokenAmounts)
public
SENDERISVALID782(_sender)
{
// first fulfills the bounty on behalf of the fulfillers
FULFILLBOUNTY596(_sender, _bountyId, _fulfillers, _data);
// then accepts the fulfillment
ACCEPTFULFILLMENT330(_sender,
_bountyId,
bounties[_bountyId].fulfillments.length - 1,
_approverId,
_tokenAmounts);
}
function CHANGEBOUNTY775( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
address payable[] memory _approvers,
string memory _data,
uint _deadline)
public
SENDERISVALID782(_sender)
{
require(_bountyId < numBounties); // makes the validateBountyArrayIndex modifier in-line to avoid stack too deep errors
require(_issuerId < bounties[_bountyId].issuers.length); // makes the validateIssuerArrayIndex modifier in-line to avoid stack too deep errors
require(_sender == bounties[_bountyId].issuers[_issuerId]); // makes the onlyIssuer modifier in-line to avoid stack too deep errors
require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck
bounties[_bountyId].issuers = _issuers;
bounties[_bountyId].approvers = _approvers;
bounties[_bountyId].deadline = _deadline;
emit BOUNTYCHANGED890(_bountyId,
_sender,
_issuers,
_approvers,
_data,
_deadline);
}
function CHANGEISSUER877( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
address payable _newIssuer)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerIdToChange)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
require(_issuerId < bounties[_bountyId].issuers.length || _issuerId == 0);
bounties[_bountyId].issuers[_issuerIdToChange] = _newIssuer;
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
}
function CHANGEAPPROVER313( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver)
external
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
VALIDATEAPPROVERARRAYINDEX32(_bountyId, _approverId)
{
bounties[_bountyId].approvers[_approverId] = _approver;
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function CHANGEISSUERANDAPPROVER5( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
uint _approverIdToChange,
address payable _issuer)
external
SENDERISVALID782(_sender)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
require(_bountyId < numBounties);
require(_approverIdToChange < bounties[_bountyId].approvers.length);
require(_issuerIdToChange < bounties[_bountyId].issuers.length);
bounties[_bountyId].issuers[_issuerIdToChange] = _issuer;
bounties[_bountyId].approvers[_approverIdToChange] = _issuer;
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function CHANGEDATA475( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
string memory _data)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
emit BOUNTYDATACHANGED202(_bountyId, _sender, _data); // The new _data is emitted within an event rather than being stored on-chain for minimized gas costs
}
function CHANGEDEADLINE144( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
uint _deadline)
external
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
bounties[_bountyId].deadline = _deadline;
emit BOUNTYDEADLINECHANGED293(_bountyId, _sender, _deadline);
}
function ADDISSUERS127( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
for (uint i = 0; i < _issuers.length; i++){
bounties[_bountyId].issuers.push(_issuers[i]);
}
emit BOUNTYISSUERSUPDATED404(_bountyId, _sender, bounties[_bountyId].issuers);
}
function ADDAPPROVERS15( //inject NONSTANDARD NAMING
address _sender,
uint _bountyId,
uint _issuerId,
address[] memory _approvers)
public
SENDERISVALID782(_sender)
VALIDATEBOUNTYARRAYINDEX962(_bountyId)
VALIDATEISSUERARRAYINDEX737(_bountyId, _issuerId)
ONLYISSUER653(_sender, _bountyId, _issuerId)
{
for (uint i = 0; i < _approvers.length; i++){
bounties[_bountyId].approvers.push(_approvers[i]);
}
emit BOUNTYAPPROVERSUPDATED564(_bountyId, _sender, bounties[_bountyId].approvers);
}
function GETBOUNTY268(uint _bountyId) //inject NONSTANDARD NAMING
external
view
returns (Bounty memory)
{
return bounties[_bountyId];
}
function TRANSFERTOKENS903(uint _bountyId, address payable _to, uint _amount) //inject NONSTANDARD NAMING
internal
{
if (bounties[_bountyId].tokenVersion == 0){
require(_amount > 0); // Sending 0 tokens should throw
require(bounties[_bountyId].balance >= _amount);
bounties[_bountyId].balance = bounties[_bountyId].balance.SUB288(_amount);
_to.transfer(_amount);
} else if (bounties[_bountyId].tokenVersion == 20){
require(_amount > 0); // Sending 0 tokens should throw
require(bounties[_bountyId].balance >= _amount);
bounties[_bountyId].balance = bounties[_bountyId].balance.SUB288(_amount);
require(ERC20Token(bounties[_bountyId].token).TRANSFER539(_to, _amount));
} else if (bounties[_bountyId].tokenVersion == 721){
require(tokenBalances[_bountyId][_amount]);
tokenBalances[_bountyId][_amount] = false; // Removes the 721 token from the balance of the bounty
ERC721BasicToken(bounties[_bountyId].token).TRANSFERFROM134(address(this),
_to,
_amount);
} else {
revert();
}
}
event BOUNTYISSUED291(uint _bountyId, address payable _creator, address payable[] _issuers, address[] _approvers, string _data, uint _deadline, address _token, uint _tokenVersion); //inject NONSTANDARD NAMING
event CONTRIBUTIONADDED888(uint _bountyId, uint _contributionId, address payable _contributor, uint _amount); //inject NONSTANDARD NAMING
event CONTRIBUTIONREFUNDED423(uint _bountyId, uint _contributionId); //inject NONSTANDARD NAMING
event CONTRIBUTIONSREFUNDED218(uint _bountyId, address _issuer, uint[] _contributionIds); //inject NONSTANDARD NAMING
event BOUNTYDRAINED424(uint _bountyId, address _issuer, uint[] _amounts); //inject NONSTANDARD NAMING
event ACTIONPERFORMED922(uint _bountyId, address _fulfiller, string _data); //inject NONSTANDARD NAMING
event BOUNTYFULFILLED198(uint _bountyId, uint _fulfillmentId, address payable[] _fulfillers, string _data, address _submitter); //inject NONSTANDARD NAMING
event FULFILLMENTUPDATED42(uint _bountyId, uint _fulfillmentId, address payable[] _fulfillers, string _data); //inject NONSTANDARD NAMING
event FULFILLMENTACCEPTED617(uint _bountyId, uint _fulfillmentId, address _approver, uint[] _tokenAmounts); //inject NONSTANDARD NAMING
event BOUNTYCHANGED890(uint _bountyId, address _changer, address payable[] _issuers, address payable[] _approvers, string _data, uint _deadline); //inject NONSTANDARD NAMING
event BOUNTYISSUERSUPDATED404(uint _bountyId, address _changer, address payable[] _issuers); //inject NONSTANDARD NAMING
event BOUNTYAPPROVERSUPDATED564(uint _bountyId, address _changer, address[] _approvers); //inject NONSTANDARD NAMING
event BOUNTYDATACHANGED202(uint _bountyId, address _changer, string _data); //inject NONSTANDARD NAMING
event BOUNTYDEADLINECHANGED293(uint _bountyId, address _changer, uint _deadline); //inject NONSTANDARD NAMING
}
contract BountiesMetaTxRelayer {
// This contract serves as a relayer for meta txns being sent to the Bounties contract
StandardBounties public bountiesContract;
mapping(address => uint) public replayNonce;
constructor(address _contract) public {
bountiesContract = StandardBounties(_contract);
}
function METAISSUEBOUNTY189( //inject NONSTANDARD NAMING
bytes memory signature,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _nonce)
public
returns (uint)
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaIssueBounty",
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_nonce));
address signer = GETSIGNER512(metaHash, signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
return bountiesContract.ISSUEBOUNTY607(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion);
}
function METAISSUEANDCONTRIBUTE154( //inject NONSTANDARD NAMING
bytes memory signature,
address payable[] memory _issuers,
address[] memory _approvers,
string memory _data,
uint _deadline,
address _token,
uint _tokenVersion,
uint _depositAmount,
uint _nonce)
public
payable
returns (uint)
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaIssueAndContribute",
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount,
_nonce));
address signer = GETSIGNER512(metaHash, signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
if (msg.value > 0){
return bountiesContract.ISSUEANDCONTRIBUTE529.value(msg.value)(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount);
} else {
return bountiesContract.ISSUEANDCONTRIBUTE529(address(uint160(signer)),
_issuers,
_approvers,
_data,
_deadline,
_token,
_tokenVersion,
_depositAmount);
}
}
function METACONTRIBUTE650( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _amount,
uint _nonce)
public
payable
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaContribute",
_bountyId,
_amount,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
if (msg.value > 0){
bountiesContract.CONTRIBUTE618.value(msg.value)(address(uint160(signer)), _bountyId, _amount);
} else {
bountiesContract.CONTRIBUTE618(address(uint160(signer)), _bountyId, _amount);
}
}
function METAREFUNDCONTRIBUTION168( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _contributionId,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundContribution",
_bountyId,
_contributionId,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDCONTRIBUTION719(signer, _bountyId, _contributionId);
}
function METAREFUNDMYCONTRIBUTIONS651( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint[] memory _contributionIds,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundMyContributions",
_bountyId,
_contributionIds,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDMYCONTRIBUTIONS1000(signer, _bountyId, _contributionIds);
}
function METAREFUNDCONTRIBUTIONS334( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint[] memory _contributionIds,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundContributions",
_bountyId,
_issuerId,
_contributionIds,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.REFUNDCONTRIBUTIONS786(signer, _bountyId, _issuerId, _contributionIds);
}
function METADRAINBOUNTY623( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint[] memory _amounts,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaDrainBounty",
_bountyId,
_issuerId,
_amounts,
_nonce));
address payable signer = address(uint160(GETSIGNER512(metaHash, _signature)));
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.DRAINBOUNTY345(signer, _bountyId, _issuerId, _amounts);
}
function METAPERFORMACTION278( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaPerformAction",
_bountyId,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.PERFORMACTION966(signer, _bountyId, _data);
}
function METAFULFILLBOUNTY952( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaFulfillBounty",
_bountyId,
_fulfillers,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.FULFILLBOUNTY596(signer, _bountyId, _fulfillers, _data);
}
function METAUPDATEFULFILLMENT854( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _fulfillmentId,
address payable[] memory _fulfillers,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaUpdateFulfillment",
_bountyId,
_fulfillmentId,
_fulfillers,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.UPDATEFULFILLMENT168(signer, _bountyId, _fulfillmentId, _fulfillers, _data);
}
function METAACCEPTFULFILLMENT218( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _fulfillmentId,
uint _approverId,
uint[] memory _tokenAmounts,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAcceptFulfillment",
_bountyId,
_fulfillmentId,
_approverId,
_tokenAmounts,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ACCEPTFULFILLMENT330(signer,
_bountyId,
_fulfillmentId,
_approverId,
_tokenAmounts);
}
function METAFULFILLANDACCEPT21( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
address payable[] memory _fulfillers,
string memory _data,
uint _approverId,
uint[] memory _tokenAmounts,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaFulfillAndAccept",
_bountyId,
_fulfillers,
_data,
_approverId,
_tokenAmounts,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.FULFILLANDACCEPT822(signer,
_bountyId,
_fulfillers,
_data,
_approverId,
_tokenAmounts);
}
function METACHANGEBOUNTY750( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
address payable[] memory _approvers,
string memory _data,
uint _deadline,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeBounty",
_bountyId,
_issuerId,
_issuers,
_approvers,
_data,
_deadline,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEBOUNTY775(signer,
_bountyId,
_issuerId,
_issuers,
_approvers,
_data,
_deadline);
}
function METACHANGEISSUER928( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _issuerIdToChange,
address payable _newIssuer,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeIssuer",
_bountyId,
_issuerId,
_issuerIdToChange,
_newIssuer,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEISSUER877(signer,
_bountyId,
_issuerId,
_issuerIdToChange,
_newIssuer);
}
function METACHANGEAPPROVER522( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeApprover",
_bountyId,
_issuerId,
_approverId,
_approver,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEAPPROVER313(signer,
_bountyId,
_issuerId,
_approverId,
_approver);
}
function METACHANGEDATA703( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
string memory _data,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeData",
_bountyId,
_issuerId,
_data,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEDATA475(signer,
_bountyId,
_issuerId,
_data);
}
function METACHANGEDEADLINE27( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
uint _deadline,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaChangeDeadline",
_bountyId,
_issuerId,
_deadline,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.CHANGEDEADLINE144(signer,
_bountyId,
_issuerId,
_deadline);
}
function METAADDISSUERS741( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address payable[] memory _issuers,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAddIssuers",
_bountyId,
_issuerId,
_issuers,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ADDISSUERS127(signer,
_bountyId,
_issuerId,
_issuers);
}
function METAADDAPPROVERS523( //inject NONSTANDARD NAMING
bytes memory _signature,
uint _bountyId,
uint _issuerId,
address[] memory _approvers,
uint256 _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaAddApprovers",
_bountyId,
_issuerId,
_approvers,
_nonce));
address signer = GETSIGNER512(metaHash, _signature);
//make sure signer doesn't come back as 0x0
require(signer != address(0));
require(_nonce == replayNonce[signer]);
//increase the nonce to prevent replay attacks
replayNonce[signer]++;
bountiesContract.ADDAPPROVERS15(signer,
_bountyId,
_issuerId,
_approvers);
}
function GETSIGNER512( //inject NONSTANDARD NAMING
bytes32 _hash,
bytes memory _signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (_signature.length != 65){
return address(0);
}
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
if (v < 27){
v += 27;
}
if (v != 27 && v != 28){
return address(0);
} else {
return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s );
}
}
} | inject NONSTANDARD NAMING | function ISCONTRACT297(address addr) internal view returns (bool) { | 12,856,781 |
/*
Copyright 2019 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.0;
pragma experimental ABIEncoderV2;
import "./Addresses.sol";
import "./LibAssetData.sol";
import "./LibTransactionDecoder.sol";
import "./LibOrderTransferSimulation.sol";
abstract contract ExternalFunctions is
Addresses
{
/// @dev Decodes the call data for an Exchange contract method call.
/// @param transactionData ABI-encoded calldata for an Exchange
/// contract method call.
/// @return functionName
/// @return orders
/// @return takerAssetFillAmounts
/// @return signatures
function decodeZeroExTransactionData(bytes memory transactionData)
public
pure
returns(
string memory functionName,
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
{
return LibTransactionDecoder.decodeZeroExTransactionData(transactionData);
}
/// @dev Decode AssetProxy identifier
/// @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC-721, ERC1155, or MultiAsset asset.
/// @return assetProxyId The AssetProxy identifier
function decodeAssetProxyId(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId
)
{
return LibAssetData.decodeAssetProxyId(assetData);
}
/// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification.
/// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded.
/// @return assetData AssetProxy-compliant data describing the asset.
function encodeERC20AssetData(address tokenAddress)
public
pure
returns (bytes memory assetData)
{
return LibAssetData.encodeERC20AssetData(tokenAddress);
}
/// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset.
/// @return assetProxyId The AssetProxy identifier
/// @return tokenAddress Address of the ERC-20 contract hosting this asset.
function decodeERC20AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress
)
{
return LibAssetData.decodeERC20AssetData(assetData);
}
/// @dev Encode ERC-721 asset data into the format described in the AssetProxy specification.
/// @param tokenAddress The address of the ERC-721 contract hosting the asset to be traded.
/// @param tokenId The identifier of the specific asset to be traded.
/// @return assetData AssetProxy-compliant asset data describing the asset.
function encodeERC721AssetData(address tokenAddress, uint256 tokenId)
public
pure
returns (bytes memory assetData)
{
return LibAssetData.encodeERC721AssetData(tokenAddress, tokenId);
}
/// @dev Decode ERC-721 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-721 asset.
/// @return assetProxyId The ERC-721 AssetProxy identifier
/// @return tokenAddress The address of the ERC-721 contract hosting this asset
/// @return tokenId The identifier of the specific asset to be traded.
function decodeERC721AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
uint256 tokenId
)
{
return LibAssetData.decodeERC721AssetData(assetData);
}
/// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification.
/// @param tokenAddress The address of the ERC-1155 contract hosting the asset(s) to be traded.
/// @param tokenIds The identifiers of the specific assets to be traded.
/// @param tokenValues The amounts of each asset to be traded.
/// @param callbackData Data to be passed to receiving contracts when a transfer is performed.
/// @return assetData AssetProxy-compliant asset data describing the set of assets.
function encodeERC1155AssetData(
address tokenAddress,
uint256[] memory tokenIds,
uint256[] memory tokenValues,
bytes memory callbackData
)
public
pure
returns (bytes memory assetData)
{
return LibAssetData.encodeERC1155AssetData(
tokenAddress,
tokenIds,
tokenValues,
callbackData
);
}
/// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification.
/// Each element of the returned arrays corresponds to the
/// same-indexed element of the other array. Return values specified as
/// `memory` are returned as pointers to locations within the memory of
/// the input parameter `assetData`.
/// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets.
/// @return assetProxyId The ERC-1155 AssetProxy identifier
/// @return tokenAddress The address of the ERC-1155 contract hosting the assets
/// @return tokenIds An array of the identifiers of the assets to be traded
/// @return tokenValues An array of asset amounts to be traded
/// @return callbackData Callback data.
function decodeERC1155AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
uint256[] memory tokenIds,
uint256[] memory tokenValues,
bytes memory callbackData
)
{
return LibAssetData.decodeERC1155AssetData(assetData);
}
/// @dev Encode data for multiple assets, per the AssetProxy contract specification.
/// @param amounts The amounts of each asset to be traded.
/// @param nestedAssetData AssetProxy-compliant data describing each asset to be traded.
/// @return assetData AssetProxy-compliant data describing the set of assets.
function encodeMultiAssetData(uint256[] memory amounts, bytes[] memory nestedAssetData)
public
pure
returns (bytes memory assetData)
{
return LibAssetData.encodeMultiAssetData(amounts, nestedAssetData);
}
/// @dev Decode multi-asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant data describing a multi-asset basket.
/// @return assetProxyId The Multi-Asset AssetProxy identifier
/// @return amounts An array of the amounts of the assets to be traded
/// @return nestedAssetData An array of the AssetProxy-compliant data
// describing each asset to be traded.
function decodeMultiAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
uint256[] memory amounts,
bytes[] memory nestedAssetData
)
{
return LibAssetData.decodeMultiAssetData(assetData);
}
/// @dev Encode StaticCall asset data into the format described in the AssetProxy contract specification.
/// @param staticCallTargetAddress Target address of StaticCall.
/// @param staticCallData Data that will be passed to staticCallTargetAddress in the StaticCall.
/// @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall return data.
/// @return assetData AssetProxy-compliant asset data describing the set of assets.
function encodeStaticCallAssetData(
address staticCallTargetAddress,
bytes memory staticCallData,
bytes32 expectedReturnDataHash
)
public
pure
returns (bytes memory assetData)
{
return LibAssetData.encodeStaticCallAssetData(
staticCallTargetAddress,
staticCallData,
expectedReturnDataHash
);
}
/// @dev Decode StaticCall asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing a StaticCall asset
/// @return assetProxyId The StaticCall AssetProxy identifier
/// @return staticCallTargetAddress The target address of the StaticCall
/// @return staticCallData The data to be passed to the target address
/// @return expectedReturnDataHash The expected Keccak-256 hash of the static call return data.
function decodeStaticCallAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address staticCallTargetAddress,
bytes memory staticCallData,
bytes32 expectedReturnDataHash
)
{
return LibAssetData.decodeStaticCallAssetData(assetData);
}
/// @dev Decode ERC20Bridge asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC20Bridge asset
/// @return assetProxyId The ERC20BridgeProxy identifier.
/// @return tokenAddress The address of the ERC20 token to transfer.
/// @return bridgeAddress the address of the bridge contract.
/// @return bridgeData Extra data to be passed to the bridge contract.
function decodeERC20BridgeAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
address bridgeAddress,
bytes memory bridgeData
)
{
return LibAssetData.decodeERC20BridgeAssetData(assetData);
}
/// @dev Reverts if assetData is not of a valid format for its given proxy id.
/// @param assetData AssetProxy compliant asset data.
function revertIfInvalidAssetData(bytes memory assetData)
public
pure
{
return LibAssetData.revertIfInvalidAssetData(assetData);
}
/// @dev Simulates the maker transfers within an order and returns the index of the first failed transfer.
/// @param order The order to simulate transfers for.
/// @param takerAddress The address of the taker that will fill the order.
/// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill.
/// @return orderTransferResults The index of the first failed transfer (or 4 if all transfers are successful).
function getSimulatedOrderMakerTransferResults(
LibOrder.Order memory order,
address takerAddress,
uint256 takerAssetFillAmount
)
public
returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults)
{
return LibOrderTransferSimulation.getSimulatedOrderMakerTransferResults(
exchangeAddress,
order,
takerAddress,
takerAssetFillAmount
);
}
/// @dev Simulates all of the transfers within an order and returns the index of the first failed transfer.
/// @param order The order to simulate transfers for.
/// @param takerAddress The address of the taker that will fill the order.
/// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill.
/// @return orderTransferResults The index of the first failed transfer (or 4 if all transfers are successful).
function getSimulatedOrderTransferResults(
LibOrder.Order memory order,
address takerAddress,
uint256 takerAssetFillAmount
)
public
returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults)
{
return LibOrderTransferSimulation.getSimulatedOrderTransferResults(
exchangeAddress,
order,
takerAddress,
takerAssetFillAmount
);
}
/// @dev Simulates all of the transfers for each given order and returns the indices of each first failed transfer.
/// @param orders Array of orders to individually simulate transfers for.
/// @param takerAddresses Array of addresses of takers that will fill each order.
/// @param takerAssetFillAmounts Array of amounts of takerAsset that will be filled for each order.
/// @return orderTransferResults The indices of the first failed transfer (or 4 if all transfers are successful) for each order.
function getSimulatedOrdersTransferResults(
LibOrder.Order[] memory orders,
address[] memory takerAddresses,
uint256[] memory takerAssetFillAmounts
)
public
returns (LibOrderTransferSimulation.OrderTransferResults[] memory orderTransferResults)
{
return LibOrderTransferSimulation.getSimulatedOrdersTransferResults(
exchangeAddress,
orders,
takerAddresses,
takerAssetFillAmounts
);
}
}
| Decode multi-asset data from the format described in the AssetProxy contract specification. assetData AssetProxy-compliant data describing a multi-asset basket. return assetProxyId The Multi-Asset AssetProxy identifier return amounts An array of the amounts of the assets to be traded return nestedAssetData An array of the AssetProxy-compliant data describing each asset to be traded. | function decodeMultiAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
uint256[] memory amounts,
bytes[] memory nestedAssetData
)
{
return LibAssetData.decodeMultiAssetData(assetData);
}
| 6,362,894 |
./full_match/1313161555/0x8B6016fb57Af5B74Aef8D9bEBEdB5551ba8deF07/sources/contracts/20230321-veXPOLAR-activation/veXPOLARDeploymentCoordinator.sol | Returns the Balancer Vault's current authorizer./ | function getAuthorizer() public view returns (ICurrentAuthorizer) {
return ICurrentAuthorizer(address(getVault().getAuthorizer()));
}
| 7,095,791 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol";
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
* @dev The State Transitioner coordinates the execution of a state transition during the evaluation of a
* fraud proof. It feeds verified input to the Execution Manager's run(), and controls a State Manager (which is
* uniquely created for each fraud proof).
* Once a fraud proof has been initialized, this contract is provided with the pre-state root and verifies
* that the OVM storage slots committed to the State Mangager are contained in that state
* This contract controls the State Manager and Execution Manager, and uses them to calculate the
* post-state root by applying the transaction. The Fraud Verifier can then check for fraud by comparing
* the calculated post-state root with the proposed post-state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner {
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_StateManager public ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase public phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/*************
* Constants *
*************/
bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")).create(address(this));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
external
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
external
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
external
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _ethContractAddress Address of the corresponding contract on L1.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
(
ovmStateManager.hasAccount(_ovmContractAddress) == false
&& ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false
),
"Account state has already been proven."
);
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
);
if (exists == true) {
// Account exists, this was an inclusion proof.
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedAccount
);
address ethContractAddress = _ethContractAddress;
if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {
// Use a known empty contract to prevent an attack in which a user provides a
// contract address here and then later deploys code to it.
ethContractAddress = 0x0000000000000000000000000000000000000000;
} else {
// Otherwise, make sure that the code at the provided eth address matches the hash
// of the code stored on L2.
require(
Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,
"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash."
);
}
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: account.nonce,
balance: account.balance,
storageRoot: account.storageRoot,
codeHash: account.codeHash,
ethAddress: ethContractAddress,
isFresh: false
})
);
} else {
// Account does not exist, this was an exclusion proof.
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);
bytes32 value;
if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {
// Storage trie was empty, so the user is always allowed to insert zero-byte values.
value = bytes32(0);
} else {
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedValue
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
storageRoot
);
if (exists == true) {
// Inclusion proof.
// Stored values are RLP encoded, with leading zeros removed.
value = Lib_BytesUtils.toBytes32PadLeft(
Lib_RLPReader.readBytes(encodedValue)
);
} else {
// Exclusion proof, can only be zero bytes.
value = bytes32(0);
}
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We require gas to complete the logic here in run() before/after execution,
// But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)
// This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first
// going into EM, then going into the code contract).
require(
gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, // 1032/1000 = 1.032 = (64/63)^2 rounded up
"Not enough gas to execute transaction deterministically."
);
iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(address(ovmExecutionManager));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
// Prevent the Execution Manager from calling this SM again.
ovmStateManager.setExecutionManager(address(0));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before committing account states."
);
require (
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account state wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
// Emit an event to help clients figure out the proof ordering.
emit AccountCommitted(
_ovmContractAddress
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot value wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(value)
),
_storageTrieWitness,
account.storageRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
// Emit an event to help clients figure out the proof ordering.
emit ContractStorageCommitted(
_ovmContractAddress,
_key
);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/* Contract Imports */
import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol";
/**
* @title OVM_StateTransitionerFactory
* @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State
* Transitioner during the initialization of a fraud proof.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {
/***************
* Constructor *
***************/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateTransitioner
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
* @return New OVM_StateTransitioner instance.
*/
function create(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
override
public
returns (
iOVM_StateTransitioner
)
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"Create can only be done by the OVM_FraudVerifier."
);
return new OVM_StateTransitioner(
_libAddressManager,
_stateTransitionIndex,
_preStateRoot,
_transactionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
interface iOVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_OVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external;
function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string _name,
address _newAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
addresses[_getNameHash(_name)] = _address;
emit AddressSet(
_name,
_address
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes('');
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key, meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path, updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
| Computes the trie root from a given path. _nodes Path to some k/v pair. _key Key for the k/v pair. return _updatedRoot Root hash for the updated trie./ Some variables to keep track of during iteration. Run through the path backwards to rebuild our root hash. Pick out the current node. Leaf nodes are already correctly encoded. Shift the key over to account for the nodes key. Shift the key over to account for the nodes key. If this node is the last element in the path, it'll be correctly encoded and we can skip this part. Re-encode the node based on the previous node. If this node is the last element in the path, it'll be correctly encoded and we can skip this part. Re-encode the node based on the previous node. | function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
for (uint256 i = _nodes.length; i > 0; i--) {
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
if (previousNodeHash.length > 0) {
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
if (previousNodeHash.length > 0) {
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
}
}
| 194,797 |
pragma solidity 0.5.17;
import "./MToken.sol";
import "./MomaPool.sol"; // unused currently
import "./Governance/Moma.sol";
import "./MomaFactoryInterface.sol";
contract MomaFarming is ExponentialNoError {
address public admin;
Moma public moma;
MomaFactoryInterface public factory;
bool public constant isMomaFarming = true;
/// @notice The initial moma index for a market
uint public constant momaInitialIndex = 1e36;
uint public momaSpeed;
uint public momaTotalWeight;
struct MarketState {
/// @notice Whether is MOMA market, used to avoid add to momaMarkets again
bool isMomaMarket;
/// @notice The market's MOMA weight, times of 1
uint weight;
/// @notice The market's block number that the supplyIndex was last updated at
uint supplyBlock;
/// @notice The market's block number that the borrowIndex was last updated at
uint borrowBlock;
/// @notice The market's last updated supplyIndex
uint supplyIndex;
/// @notice The market's last updated borrowIndex
uint borrowIndex;
/// @notice The market's MOMA supply index of each supplier as of the last time they accrued MOMA
mapping(address => uint) supplierIndex;
/// @notice The market's MOMA borrow index of each borrower as of the last time they accrued MOMA
mapping(address => uint) borrowerIndex;
}
/// @notice Each MOMA pool's each momaMarket's MarketState
mapping(address => mapping(address => MarketState)) public marketStates;
/// @notice Each MOMA pool's momaMarkets list
mapping(address => MToken[]) public momaMarkets;
/// @notice Whether is MOMA lending pool
mapping(address => bool) public isMomaLendingPool;
/// @notice Whether is MOMA pool, used to avoid add to momaPools again
mapping(address => bool) public isMomaPool;
/// @notice A list of all MOMA pools
MomaPool[] public momaPools;
/// @notice The MOMA accrued but not yet transferred to each user
mapping(address => uint) public momaAccrued;
/// @notice Emitted when MOMA is distributed to a supplier
event DistributedSupplier(address indexed pool, MToken indexed mToken, address indexed supplier, uint momaDelta, uint marketSupplyIndex);
/// @notice Emitted when MOMA is distributed to a borrower
event DistributedBorrower(address indexed pool, MToken indexed mToken, address indexed borrower, uint momaDelta, uint marketBorrowIndex);
/// @notice Emitted when MOMA is claimed by user
event MomaClaimed(address user, uint accrued, uint claimed, uint notClaimed);
/// @notice Emitted when admin is changed by admin
event NewAdmin(address oldAdmin, address newAdmin);
/// @notice Emitted when factory is changed by admin
event NewFactory(MomaFactoryInterface oldFactory, MomaFactoryInterface newFactory);
/// @notice Emitted when momaSpeed is changed by admin
event NewMomaSpeed(uint oldMomaSpeed, uint newMomaSpeed);
/// @notice Emitted when a new MOMA weight is changed by admin
event NewMarketWeight(address indexed pool, MToken indexed mToken, uint oldWeight, uint newWeight);
/// @notice Emitted when a new MOMA total weight is updated
event NewTotalWeight(uint oldTotalWeight, uint newTotalWeight);
/// @notice Emitted when a new MOMA market is added to momaMarkets
event NewMomaMarket(address indexed pool, MToken indexed mToken);
/// @notice Emitted when a new MOMA pool is added to momaPools
event NewMomaPool(address indexed pool);
/// @notice Emitted when MOMA is granted by admin
event MomaGranted(address recipient, uint amount);
constructor (Moma _moma, MomaFactoryInterface _factory) public {
admin = msg.sender;
moma = _moma;
factory = _factory;
}
/*** Internal Functions ***/
/**
* @notice Calculate the new MOMA supply index and block of this market
* @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0
* @param pool The pool whose supply index to calculate
* @param mToken The market whose supply index to calculate
* @return (new index, new block)
*/
function newMarketSupplyStateInternal(address pool, MToken mToken) internal view returns (uint, uint) {
MarketState storage state = marketStates[pool][address(mToken)];
uint _index = state.supplyIndex;
uint _block = state.supplyBlock;
uint blockNumber = getBlockNumber();
// Non-moma market's weight is always 0, will only update block
if (blockNumber > _block) {
uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight);
uint deltaBlocks = sub_(blockNumber, _block);
uint _momaAccrued = mul_(deltaBlocks, speed);
uint supplyTokens = mToken.totalSupply();
Double memory ratio = supplyTokens > 0 ? fraction(_momaAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: _index}), ratio);
_index = index.mantissa;
_block = blockNumber;
}
return (_index, _block);
}
/**
* @notice Accrue MOMA to the market by updating the supply state
* @dev To avoid revert: no over/underflow
* @param pool The pool whose supply state to update
* @param mToken The market whose supply state to update
*/
function updateMarketSupplyStateInternal(address pool, MToken mToken) internal {
MarketState storage state = marketStates[pool][address(mToken)];
// Non-moma market's weight will always be 0, 0 weight moma market will also update nothing
if (state.weight > 0) { // momaTotalWeight > 0
(uint _index, uint _block) = newMarketSupplyStateInternal(pool, mToken);
state.supplyIndex = _index;
state.supplyBlock = _block;
}
}
/**
* @notice Calculate the new MOMA borrow index and block of this market
* @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0, marketBorrowIndex > 0
* @param pool The pool whose borrow index to calculate
* @param mToken The market whose borrow index to calculate
* @param marketBorrowIndex The market borrow index
* @return (new index, new block)
*/
function newMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal view returns (uint, uint) {
MarketState storage state = marketStates[pool][address(mToken)];
uint _index = state.borrowIndex;
uint _block = state.borrowBlock;
uint blockNumber = getBlockNumber();
// Non-moma market's weight is always 0, will only update block
if (blockNumber > _block) {
uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight);
uint deltaBlocks = sub_(blockNumber, _block);
uint _momaAccrued = mul_(deltaBlocks, speed);
uint borrowAmount = div_(mToken.totalBorrows(), Exp({mantissa: marketBorrowIndex}));
Double memory ratio = borrowAmount > 0 ? fraction(_momaAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: _index}), ratio);
_index = index.mantissa;
_block = blockNumber;
}
return (_index, _block);
}
/**
* @notice Accrue MOMA to the market by updating the borrow state
* @dev To avoid revert: no over/underflow
* @param pool The pool whose borrow state to update
* @param mToken The market whose borrow state to update
* @param marketBorrowIndex The market borrow index
*/
function updateMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal {
if (isMomaLendingPool[pool] == true) {
MarketState storage state = marketStates[pool][address(mToken)];
// Non-moma market's weight will always be 0, 0 weight moma market will also update nothing
if (state.weight > 0 && marketBorrowIndex > 0) { // momaTotalWeight > 0
(uint _index, uint _block) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex);
state.borrowIndex = _index;
state.borrowBlock = _block;
}
}
}
/**
* @notice Calculate MOMA accrued by a supplier
* @dev To avoid revert: no over/underflow
* @param pool The pool in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
* @param supplyIndex The MOMA supply index of this market in Double type
* @return (new supplierAccrued, new supplierDelta)
*/
function newSupplierMomaInternal(address pool, MToken mToken, address supplier, Double memory supplyIndex) internal view returns (uint, uint) {
Double memory supplierIndex = Double({mantissa: marketStates[pool][address(mToken)].supplierIndex[supplier]});
uint _supplierAccrued = momaAccrued[supplier];
uint _supplierDelta = 0;
// supply before set moma market can still get rewards start from set block
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = momaInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = mToken.balanceOf(supplier);
_supplierDelta = mul_(supplierTokens, deltaIndex);
_supplierAccrued = add_(_supplierAccrued, _supplierDelta);
return (_supplierAccrued, _supplierDelta);
}
/**
* @notice Distribute MOMA accrued by a supplier
* @dev To avoid revert: no over/underflow
* @param pool The pool in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOMA to
*/
function distributeSupplierMomaInternal(address pool, MToken mToken, address supplier) internal {
MarketState storage state = marketStates[pool][address(mToken)];
if (state.supplyIndex > state.supplierIndex[supplier]) {
Double memory supplyIndex = Double({mantissa: state.supplyIndex});
(uint _supplierAccrued, uint _supplierDelta) = newSupplierMomaInternal(pool, mToken, supplier, supplyIndex);
state.supplierIndex[supplier] = supplyIndex.mantissa;
momaAccrued[supplier] = _supplierAccrued;
emit DistributedSupplier(pool, mToken, supplier, _supplierDelta, supplyIndex.mantissa);
}
}
/**
* @notice Calculate MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol
* @dev To avoid revert: marketBorrowIndex > 0
* @param pool The pool in which the borrower is interacting
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOMA to
* @param marketBorrowIndex The market borrow index
* @param borrowIndex The MOMA borrow index of this market in Double type
* @return (new borrowerAccrued, new borrowerDelta)
*/
function newBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex, Double memory borrowIndex) internal view returns (uint, uint) {
Double memory borrowerIndex = Double({mantissa: marketStates[pool][address(mToken)].borrowerIndex[borrower]});
uint _borrowerAccrued = momaAccrued[borrower];
uint _borrowerDelta = 0;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(mToken.borrowBalanceStored(borrower), Exp({mantissa: marketBorrowIndex}));
_borrowerDelta = mul_(borrowerAmount, deltaIndex);
_borrowerAccrued = add_(_borrowerAccrued, _borrowerDelta);
}
return (_borrowerAccrued, _borrowerDelta);
}
/**
* @notice Distribute MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol
* @dev To avoid revert: no over/underflow
* @param pool The pool in which the borrower is interacting
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex) internal {
if (isMomaLendingPool[pool] == true) {
MarketState storage state = marketStates[pool][address(mToken)];
if (state.borrowIndex > state.borrowerIndex[borrower] && marketBorrowIndex > 0) {
Double memory borrowIndex = Double({mantissa: state.borrowIndex});
(uint _borrowerAccrued, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, borrower, marketBorrowIndex, borrowIndex);
state.borrowerIndex[borrower] = borrowIndex.mantissa;
momaAccrued[borrower] = _borrowerAccrued;
emit DistributedBorrower(pool, mToken, borrower, _borrowerDelta, borrowIndex.mantissa);
}
}
}
/**
* @notice Transfer MOMA to the user
* @dev Note: If there is not enough MOMA, will do not perform the transfer
* @param user The address of the user to transfer MOMA to
* @param amount The amount of token to (possibly) transfer
* @return The amount of token which was NOT transferred to the user
*/
function grantMomaInternal(address user, uint amount) internal returns (uint) {
uint remaining = moma.balanceOf(address(this));
if (amount > 0 && amount <= remaining) {
moma.transfer(user, amount);
return 0;
}
return amount;
}
/**
* @notice Claim all the MOMA have been distributed to user
* @param user The address to claim MOMA for
*/
function claim(address user) internal {
uint accrued = momaAccrued[user];
uint notClaimed = grantMomaInternal(user, accrued);
momaAccrued[user] = notClaimed;
uint claimed = sub_(accrued, notClaimed);
emit MomaClaimed(user, accrued, claimed, notClaimed);
}
/**
* @notice Distribute all the MOMA accrued to user in the specified markets of specified pool
* @param user The address to distribute MOMA for
* @param pool The moma pool to distribute MOMA in
* @param mTokens The list of markets to distribute MOMA in
* @param suppliers Whether or not to distribute MOMA earned by supplying
* @param borrowers Whether or not to distribute MOMA earned by borrowing
*/
function distribute(address user, address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) internal {
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
if (suppliers == true) {
updateMarketSupplyStateInternal(pool, mToken);
distributeSupplierMomaInternal(pool, mToken, user);
}
if (borrowers == true && isMomaLendingPool[pool] == true) {
uint borrowIndex = mToken.borrowIndex();
updateMarketBorrowStateInternal(pool, mToken, borrowIndex);
distributeBorrowerMomaInternal(pool, mToken, user, borrowIndex);
}
}
}
/**
* @notice Distribute all the MOMA accrued to user in all markets of specified pools
* @param user The address to distribute MOMA for
* @param pools The list of moma pools to distribute MOMA
* @param suppliers Whether or not to distribute MOMA earned by supplying
* @param borrowers Whether or not to distribute MOMA earned by borrowing
*/
function distribute(address user, MomaPool[] memory pools, bool suppliers, bool borrowers) internal {
for (uint i = 0; i < pools.length; i++) {
address pool = address(pools[i]);
distribute(user, pool, momaMarkets[pool], suppliers, borrowers);
}
}
/*** Factory Functions ***/
/**
* @notice Update pool market's borrowBlock when it upgrades to lending pool in factory
* @dev Note: can only call once by factory
* @param pool The pool to upgrade
*/
function upgradeLendingPool(address pool) external {
require(msg.sender == address(factory), 'MomaFarming: not factory');
require(isMomaLendingPool[pool] == false, 'MomaFarming: can only upgrade once');
uint blockNumber = getBlockNumber();
MToken[] memory mTokens = momaMarkets[pool];
for (uint i = 0; i < mTokens.length; i++) {
MarketState storage state = marketStates[pool][address(mTokens[i])];
state.borrowBlock = blockNumber; // if state.weight > 0 ?
}
isMomaLendingPool[pool] = true;
}
/*** Called Functions ***/
/**
* @notice Accrue MOMA to the market by updating the supply state
* @param mToken The market whose supply state to update
*/
function updateMarketSupplyState(address mToken) external {
require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool');
updateMarketSupplyStateInternal(msg.sender, MToken(mToken));
}
/**
* @notice Accrue MOMA to the market by updating the borrow state
* @param mToken The market whose borrow state to update
* @param marketBorrowIndex The market borrow index
*/
function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external {
require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool');
updateMarketBorrowStateInternal(msg.sender, MToken(mToken), marketBorrowIndex);
}
/**
* @notice Distribute MOMA accrued by a supplier
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOMA to
*/
function distributeSupplierMoma(address mToken, address supplier) external {
require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool');
distributeSupplierMomaInternal(msg.sender, MToken(mToken), supplier);
}
/**
* @notice Distribute MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external {
require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool');
distributeBorrowerMomaInternal(msg.sender, MToken(mToken), borrower, marketBorrowIndex);
}
/**
* @notice Distribute all the MOMA accrued to user in specified markets of specified pool and claim
* @param pool The moma pool to distribute MOMA in
* @param mTokens The list of markets to distribute MOMA in
* @param suppliers Whether or not to distribute MOMA earned by supplying
* @param borrowers Whether or not to distribute MOMA earned by borrowing
*/
function dclaim(address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) public {
distribute(msg.sender, pool, mTokens, suppliers, borrowers);
claim(msg.sender);
}
/**
* @notice Distribute all the MOMA accrued to user in all markets of specified pools and claim
* @param pools The list of moma pools to distribute and claim MOMA
* @param suppliers Whether or not to distribute MOMA earned by supplying
* @param borrowers Whether or not to distribute MOMA earned by borrowing
*/
function dclaim(MomaPool[] memory pools, bool suppliers, bool borrowers) public {
distribute(msg.sender, pools, suppliers, borrowers);
claim(msg.sender);
}
/**
* @notice Distribute all the MOMA accrued to user in all markets of all pools and claim
* @param suppliers Whether or not to distribute MOMA earned by supplying
* @param borrowers Whether or not to distribute MOMA earned by borrowing
*/
function dclaim(bool suppliers, bool borrowers) public {
distribute(msg.sender, momaPools, suppliers, borrowers);
claim(msg.sender);
}
/**
* @notice Claim all the MOMA have been distributed to user
*/
function claim() public {
claim(msg.sender);
}
/*** View Functions ***/
/**
* @notice Calculate the speed of a moma market
* @param pool The moma pool to calculate speed
* @param mToken The moma market to calculate speed
* @return The mama market speed
*/
function getMarketSpeed(address pool, address mToken) public view returns (uint) {
if (momaTotalWeight == 0) return 0;
return div_(mul_(momaSpeed, marketStates[pool][mToken].weight), momaTotalWeight);
}
/**
* @notice Return all of the moma pools
* @dev The automatic getter may be used to access an individual pool
* @return The list of pool addresses
*/
function getAllMomaPools() public view returns (MomaPool[] memory) {
return momaPools;
}
/**
* @notice Return the total number of moma pools
* @return The number of mama pools
*/
function getMomaPoolNum() public view returns (uint) {
return momaPools.length;
}
/**
* @notice Return all of the moma markets of the specified pool
* @dev The automatic getter may be used to access an individual market
* @param pool The moma pool to get moma markets
* @return The list of market addresses
*/
function getMomaMarkets(address pool) public view returns (MToken[] memory) {
return momaMarkets[pool];
}
/**
* @notice Return the total number of moma markets of all pools
* @return The number of total mama markets
*/
function getMomaMarketNum() public view returns (uint num) {
for (uint i = 0; i < momaPools.length; i++) {
num += momaMarkets[address(momaPools[i])].length;
}
}
/**
* @notice Weather this is a moma market
* @param pool The moma pool of this market
* @param mToken The moma market to ask
* @return true or false
*/
function isMomaMarket(address pool, address mToken) public view returns (bool) {
return marketStates[pool][mToken].isMomaMarket;
}
function isLendingPool(address pool) public view returns (bool) {
return factory.isLendingPool(pool);
}
/**
* @notice Calculate undistributed MOMA accrued by the user in specified market of specified pool
* @param user The address to calculate MOMA for
* @param pool The moma pool to calculate MOMA
* @param mToken The market to calculate MOMA
* @param suppliers Whether or not to calculate MOMA earned by supplying
* @param borrowers Whether or not to calculate MOMA earned by borrowing
* @return The amount of undistributed MOMA of this user
*/
function undistributed(address user, address pool, MToken mToken, bool suppliers, bool borrowers) public view returns (uint) {
uint accrued;
uint _index;
MarketState storage state = marketStates[pool][address(mToken)];
if (suppliers == true) {
if (state.weight > 0) { // momaTotalWeight > 0
(_index, ) = newMarketSupplyStateInternal(pool, mToken);
} else {
_index = state.supplyIndex;
}
if (_index > state.supplierIndex[user]) {
(, accrued) = newSupplierMomaInternal(pool, mToken, user, Double({mantissa: _index}));
}
}
if (borrowers == true && isMomaLendingPool[pool] == true) {
uint marketBorrowIndex = mToken.borrowIndex();
if (marketBorrowIndex > 0) {
if (state.weight > 0) { // momaTotalWeight > 0
(_index, ) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex);
} else {
_index = state.borrowIndex;
}
if (_index > state.borrowerIndex[user]) {
(, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, user, marketBorrowIndex, Double({mantissa: _index}));
accrued = add_(accrued, _borrowerDelta);
}
}
}
return accrued;
}
/**
* @notice Calculate undistributed MOMA accrued by the user in all markets of specified pool
* @param user The address to calculate MOMA for
* @param pool The moma pool to calculate MOMA
* @param suppliers Whether or not to calculate MOMA earned by supplying
* @param borrowers Whether or not to calculate MOMA earned by borrowing
* @return The amount of undistributed MOMA of this user in each market
*/
function undistributed(address user, address pool, bool suppliers, bool borrowers) public view returns (uint[] memory) {
MToken[] memory mTokens = momaMarkets[pool];
uint[] memory accrued = new uint[](mTokens.length);
for (uint i = 0; i < mTokens.length; i++) {
accrued[i] = undistributed(user, pool, mTokens[i], suppliers, borrowers);
}
return accrued;
}
/*** Admin Functions ***/
/**
* @notice Set the new admin address
* @param newAdmin The new admin address
*/
function _setAdmin(address newAdmin) external {
require(msg.sender == admin && newAdmin != address(0), 'MomaFarming: admin check');
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
/**
* @notice Set the new factory contract
* @param newFactory The new factory contract address
*/
function _setFactory(MomaFactoryInterface newFactory) external {
require(msg.sender == admin && address(newFactory) != address(0), 'MomaFarming: admin check');
require(newFactory.isMomaFactory(), 'MomaFarming: not moma factory');
MomaFactoryInterface oldFactory = factory;
factory = newFactory;
emit NewFactory(oldFactory, newFactory);
}
/**
* @notice Update state for all MOMA markets of all pools
* @dev Note: Be careful of gas spending!
*/
function updateAllMomaMarkets() public {
for (uint i = 0; i < momaPools.length; i++) {
address pool = address(momaPools[i]);
MToken[] memory mTokens = momaMarkets[pool];
for (uint j = 0; j < mTokens.length; j++) {
MToken mToken = mTokens[j];
updateMarketSupplyStateInternal(pool, mToken);
if (isMomaLendingPool[pool] == true) {
uint borrowIndex = mToken.borrowIndex();
updateMarketBorrowStateInternal(pool, mToken, borrowIndex);
}
}
}
}
/**
* @notice Set the new momaSpeed for all MOMA markets of all pools
* @dev Note: can call at any time, but must update state of all moma markets first
* @param newMomaSpeed The new momaSpeed
*/
function _setMomaSpeed(uint newMomaSpeed) public {
require(msg.sender == admin, 'MomaFarming: admin check');
// Update state for all MOMA markets of all pools
updateAllMomaMarkets();
uint oldMomaSpeed = momaSpeed;
momaSpeed = newMomaSpeed;
emit NewMomaSpeed(oldMomaSpeed, newMomaSpeed);
}
/**
* @notice Set MOMA markets' weight, will also mark as MOMA market in the first time
* @dev Note: can call at any time, but must update state of all moma markets first
* @param pool The address of the pool
* @param mTokens The markets to set weigh
* @param newWeights The new weights, 0 means no new MOMA farm
*/
function _setMarketsWeight(address payable pool, MToken[] memory mTokens, uint[] memory newWeights) public {
require(msg.sender == admin, 'MomaFarming: admin check');
require(factory.isMomaPool(pool), 'MomaFarming: not moma pool');
require(mTokens.length == newWeights.length, "MomaFarming: param length dismatch");
// Update state for all MOMA markets of all pools
updateAllMomaMarkets();
uint oldWeightTotal;
uint newWeightTotal;
uint blockNumber = getBlockNumber();
// Update state for all MOMA markets to be setted
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
MarketState storage state = marketStates[pool][address(mToken)];
// add this market to momaMarkets if first set
if (!state.isMomaMarket) {
(bool isListed, ) = MomaMasterV1Storage(pool).markets(address(mToken));
require(isListed == true, "market is not listed");
state.isMomaMarket = true;
momaMarkets[pool].push(mToken);
emit NewMomaMarket(pool, mToken);
// set initial index of this market
state.supplyIndex = momaInitialIndex;
state.borrowIndex = momaInitialIndex;
}
uint oldWeight = state.weight;
oldWeightTotal = add_(oldWeightTotal, oldWeight);
newWeightTotal = add_(newWeightTotal, newWeights[i]);
// update weight and block of this market
state.weight = newWeights[i];
state.supplyBlock = blockNumber;
state.borrowBlock = blockNumber;
emit NewMarketWeight(pool, mToken, oldWeight, newWeights[i]);
}
uint oldMomaTotalWeight = momaTotalWeight;
// update momaTotalWeight
momaTotalWeight = add_(sub_(momaTotalWeight, oldWeightTotal), newWeightTotal);
emit NewTotalWeight(oldMomaTotalWeight, momaTotalWeight);
// add this pool to momaPools if first set
if (!isMomaPool[pool]) {
isMomaPool[pool] = true;
momaPools.push(MomaPool(pool));
emit NewMomaPool(pool);
// mark to lending pool
if (isLendingPool(pool)) isMomaLendingPool[pool] = true;
}
}
/**
* @notice Transfer MOMA to the recipient
* @dev Note: If there is not enough MOMA, we do not perform the transfer
* @param recipient The address of the recipient to transfer MOMA to
* @param amount The amount of MOMA to (possibly) transfer
*/
function _grantMoma(address recipient, uint amount) public {
require(msg.sender == admin, 'MomaFarming: only admin can grant token');
uint notTransfered = grantMomaInternal(recipient, amount);
require(notTransfered == 0, 'MomaFarming: insufficient MOMA for grant');
emit MomaGranted(recipient, amount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
| Set MOMA markets' weight, will also mark as MOMA market in the first time Note: can call at any time, but must update state of all moma markets first pool The address of the pool mTokens The markets to set weigh newWeights The new weights, 0 means no new MOMA farm/ Update state for all MOMA markets of all pools Update state for all MOMA markets to be setted | function _setMarketsWeight(address payable pool, MToken[] memory mTokens, uint[] memory newWeights) public {
require(msg.sender == admin, 'MomaFarming: admin check');
require(factory.isMomaPool(pool), 'MomaFarming: not moma pool');
require(mTokens.length == newWeights.length, "MomaFarming: param length dismatch");
updateAllMomaMarkets();
uint oldWeightTotal;
uint newWeightTotal;
uint blockNumber = getBlockNumber();
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
MarketState storage state = marketStates[pool][address(mToken)];
if (!state.isMomaMarket) {
(bool isListed, ) = MomaMasterV1Storage(pool).markets(address(mToken));
require(isListed == true, "market is not listed");
state.isMomaMarket = true;
momaMarkets[pool].push(mToken);
emit NewMomaMarket(pool, mToken);
state.supplyIndex = momaInitialIndex;
state.borrowIndex = momaInitialIndex;
}
uint oldWeight = state.weight;
oldWeightTotal = add_(oldWeightTotal, oldWeight);
newWeightTotal = add_(newWeightTotal, newWeights[i]);
state.supplyBlock = blockNumber;
state.borrowBlock = blockNumber;
emit NewMarketWeight(pool, mToken, oldWeight, newWeights[i]);
}
uint oldMomaTotalWeight = momaTotalWeight;
emit NewTotalWeight(oldMomaTotalWeight, momaTotalWeight);
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
MarketState storage state = marketStates[pool][address(mToken)];
if (!state.isMomaMarket) {
(bool isListed, ) = MomaMasterV1Storage(pool).markets(address(mToken));
require(isListed == true, "market is not listed");
state.isMomaMarket = true;
momaMarkets[pool].push(mToken);
emit NewMomaMarket(pool, mToken);
state.supplyIndex = momaInitialIndex;
state.borrowIndex = momaInitialIndex;
}
uint oldWeight = state.weight;
oldWeightTotal = add_(oldWeightTotal, oldWeight);
newWeightTotal = add_(newWeightTotal, newWeights[i]);
state.supplyBlock = blockNumber;
state.borrowBlock = blockNumber;
emit NewMarketWeight(pool, mToken, oldWeight, newWeights[i]);
}
uint oldMomaTotalWeight = momaTotalWeight;
emit NewTotalWeight(oldMomaTotalWeight, momaTotalWeight);
state.weight = newWeights[i];
momaTotalWeight = add_(sub_(momaTotalWeight, oldWeightTotal), newWeightTotal);
if (!isMomaPool[pool]) {
isMomaPool[pool] = true;
momaPools.push(MomaPool(pool));
emit NewMomaPool(pool);
if (isLendingPool(pool)) isMomaLendingPool[pool] = true;
}
}
| 12,691,543 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol';
import './interfaces/IToken.sol';
import './interfaces/IAuction.sol';
import './interfaces/IStaking.sol';
import './interfaces/IStakingV1.sol';
contract Staking is IStaking, Initializable, AccessControlUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/** Events */
event Stake(
address indexed account,
uint256 indexed sessionId,
uint256 amount,
uint256 start,
uint256 end,
uint256 shares
);
event MaxShareUpgrade(
address indexed account,
uint256 indexed sessionId,
uint256 amount,
uint256 newAmount,
uint256 shares,
uint256 newShares,
uint256 start,
uint256 end
);
event Unstake(
address indexed account,
uint256 indexed sessionId,
uint256 amount,
uint256 start,
uint256 end,
uint256 shares
);
event MakePayout(
uint256 indexed value,
uint256 indexed sharesTotalSupply,
uint256 indexed time
);
event DailyBurn(
uint256 indexed value,
uint256 indexed totalSupply,
uint256 indexed time
);
event AccountRegistered(
address indexed account,
uint256 indexed totalShares
);
event WithdrawLiquidDiv(
address indexed account,
address indexed tokenAddress,
uint256 indexed interest
);
/** Structs */
struct Payout {
uint256 payout;
uint256 sharesTotalSupply;
}
struct Session {
uint256 amount;
uint256 start;
uint256 end;
uint256 shares;
uint256 firstPayout;
uint256 lastPayout;
bool withdrawn;
uint256 payout;
}
struct Addresses {
address mainToken;
address auction;
address subBalances;
}
struct BPDPool {
uint96[5] pool;
uint96[5] shares;
}
struct BPDPool128 {
uint128[5] pool;
uint128[5] shares;
}
Addresses public addresses;
IStakingV1 public stakingV1;
/** Roles */
bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE');
bytes32 public constant EXTERNAL_STAKER_ROLE =
keccak256('EXTERNAL_STAKER_ROLE');
bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE');
/** Public Variables */
uint256 public shareRate; //shareRate used to calculate the number of shares
uint256 public sharesTotalSupply; //total shares supply
uint256 public nextPayoutCall; //used to calculate when the daily makePayout() should run
uint256 public stepTimestamp; // 24h * 60 * 60
uint256 public startContract; //time the contract started
uint256 public globalPayout;
uint256 public globalPayin;
uint256 public lastSessionId; //the ID of the last stake
uint256 public lastSessionIdV1; //the ID of the last stake from layer 1 staking contract
/** Mappings / Arrays */
// individual staking sessions
mapping(address => mapping(uint256 => Session)) public sessionDataOf;
//array with staking sessions of an address
mapping(address => uint256[]) public sessionsOf;
//array with daily payouts
Payout[] public payouts;
/** Booleans */
bool public init_;
uint256 public basePeriod; //350 days, time of the first BPD
uint256 public totalStakedAmount; //total amount of staked AXN
bool private maxShareEventActive; //true if maxShare upgrade is enabled
uint16 private maxShareMaxDays; //maximum number of days a stake length can be in order to qualify for maxShare upgrade
uint256 private shareRateScalingFactor; //scaling factor, default 1 to be used on the shareRate calculation
uint256 internal totalVcaRegisteredShares; //total number of shares from accounts that registered for the VCA
mapping(address => uint256) internal tokenPricePerShare; //price per share for every token that is going to be offered as divident through the VCA
EnumerableSetUpgradeable.AddressSet internal divTokens; //list of dividends tokens
//keep track if an address registered for VCA
mapping(address => bool) internal isVcaRegistered;
//total shares of active stakes for an address
mapping(address => uint256) internal totalSharesOf;
//mapping address-> VCA token used for VCA divs calculation. The way the system works is that deductBalances is starting as totalSharesOf x price of the respective token. So when the token price appreciates, the interest earned is the difference between totalSharesOf x new price - deductBalance [respective token]
mapping(address => mapping(address => uint256)) internal deductBalances;
bool internal paused;
BPDPool bpd;
BPDPool128 bpd128;
/* New variables must go below here. */
modifier onlyManager() {
require(hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager');
_;
}
modifier onlyMigrator() {
require(
hasRole(MIGRATOR_ROLE, _msgSender()),
'Caller is not a migrator'
);
_;
}
modifier onlyExternalStaker() {
require(
hasRole(EXTERNAL_STAKER_ROLE, _msgSender()),
'Caller is not a external staker'
);
_;
}
modifier pausable() {
require(
paused == false || hasRole(MIGRATOR_ROLE, _msgSender()),
'Contract is paused'
);
_;
}
function initialize(address _manager, address _migrator)
public
initializer
{
_setupRole(MANAGER_ROLE, _manager);
_setupRole(MIGRATOR_ROLE, _migrator);
init_ = false;
}
// @param account {address} - address of account
function sessionsOf_(address account)
external
view
returns (uint256[] memory)
{
return sessionsOf[account];
}
//staking function which receives AXN and creates the stake - takes as param the amount of AXN and the number of days to be staked
//staking days need to be >0 and lower than max days which is 5555
// @param amount {uint256} - AXN amount to be staked
// @param stakingDays {uint256} - number of days to be staked
function stake(uint256 amount, uint256 stakingDays) external pausable {
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
//call stake internal method
stakeInternal(amount, stakingDays, msg.sender);
//on stake axion gets burned
IToken(addresses.mainToken).burn(msg.sender, amount);
}
//external stake creates a stake for a different account than the caller. It takes an extra param the staker address
// @param amount {uint256} - AXN amount to be staked
// @param stakingDays {uint256} - number of days to be staked
// @param staker {address} - account address to create the stake for
function externalStake(
uint256 amount,
uint256 stakingDays,
address staker
) external override onlyExternalStaker pausable {
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
stakeInternal(amount, stakingDays, staker);
}
// @param amount {uint256} - AXN amount to be staked
// @param stakingDays {uint256} - number of days to be staked
// @param staker {address} - account address to create the stake for
function stakeInternal(
uint256 amount,
uint256 stakingDays,
address staker
) internal {
//once a day we need to call makePayout which takes the interest earned for the last day and adds it into the payout array
if (now >= nextPayoutCall) makePayout();
//ensure the user is registered for VCA if not call it
if (isVcaRegistered[staker] == false)
setTotalSharesOfAccountInternal(staker);
//time of staking start is now
uint256 start = now;
//time of stake end is now + number of days * stepTimestamp which is 24 hours
uint256 end = now.add(stakingDays.mul(stepTimestamp));
//increase the last stake ID
lastSessionId = lastSessionId.add(1);
stakeInternalCommon(
lastSessionId,
amount,
start,
end,
stakingDays,
payouts.length,
staker
);
}
//payment function uses param address and amount to be paid. Amount is minted to address
// @param to {address} - account address to send the payment to
// @param amount {uint256} - AXN amount to be paid
function _initPayout(address to, uint256 amount) internal {
IToken(addresses.mainToken).mint(to, amount);
// globalPayout = globalPayout.add(amount);
}
//staking interest calculation goes through the payout array and calculates the interest based on the number of shares the user has and the payout for every day
// @param firstPayout {uint256} - id of the first day of payout for the stake
// @param lastPayout {uint256} - id of the last day of payout for the stake
// @param shares {uint256} - number of shares of the stake
function calculateStakingInterest(
uint256 firstPayout,
uint256 lastPayout,
uint256 shares
) public view returns (uint256) {
uint256 stakingInterest;
//calculate lastIndex as minimum of lastPayout from stake session and current day (payouts.length).
uint256 lastIndex = MathUpgradeable.min(payouts.length, lastPayout);
for (uint256 i = firstPayout; i < lastIndex; i++) {
uint256 payout =
payouts[i].payout.mul(shares).div(payouts[i].sharesTotalSupply);
stakingInterest = stakingInterest.add(payout);
}
return stakingInterest;
}
//unstake function
// @param sessionID {uint256} - id of the stake
function unstake(uint256 sessionId) external pausable {
Session storage session = sessionDataOf[msg.sender][sessionId];
//ensure the stake hasn't been withdrawn before
require(
session.shares != 0 && session.withdrawn == false,
'Staking: Stake withdrawn or not set'
);
uint256 actualEnd = now;
//calculate the amount the stake earned; to be paid
uint256 amountOut = unstakeInternal(session, sessionId, actualEnd);
// To account
_initPayout(msg.sender, amountOut);
}
//unstake function for layer1 stakes
// @param sessionID {uint256} - id of the layer 1 stake
function unstakeV1(uint256 sessionId) external pausable {
//lastSessionIdv1 is the last stake ID from v1 layer
require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId');
Session storage session = sessionDataOf[msg.sender][sessionId];
// Unstaked already
require(
session.shares == 0 && session.withdrawn == false,
'Staking: Stake withdrawn'
);
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(msg.sender, sessionId);
// Unstaked in v1 / doesn't exist
require(shares != 0, 'Staking: Stake withdrawn or not set');
uint256 stakingDays = (end - start) / stepTimestamp;
uint256 lastPayout = stakingDays + firstPayout;
uint256 actualEnd = now;
//calculate amount to be paid
uint256 amountOut =
unstakeV1Internal(
sessionId,
amount,
start,
end,
actualEnd,
shares,
firstPayout,
lastPayout
);
// To account
_initPayout(msg.sender, amountOut);
}
//calculate the amount the stake earned and any penalty because of early/late unstake
// @param amount {uint256} - amount of AXN staked
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
// @param stakingInterest {uint256} - interest earned of the stake
function getAmountOutAndPenalty(
uint256 amount,
uint256 start,
uint256 end,
uint256 stakingInterest
) public view returns (uint256, uint256) {
uint256 stakingSeconds = end.sub(start);
uint256 stakingDays = stakingSeconds.div(stepTimestamp);
uint256 secondsStaked = now.sub(start);
uint256 daysStaked = secondsStaked.div(stepTimestamp);
uint256 amountAndInterest = amount.add(stakingInterest);
// Early
if (stakingDays > daysStaked) {
uint256 payOutAmount =
amountAndInterest.mul(secondsStaked).div(stakingSeconds);
uint256 earlyUnstakePenalty = amountAndInterest.sub(payOutAmount);
return (payOutAmount, earlyUnstakePenalty);
// In time
} else if (daysStaked < stakingDays.add(14)) {
return (amountAndInterest, 0);
// Late
} else if (daysStaked < stakingDays.add(714)) {
return (amountAndInterest, 0);
/** Remove late penalties for now */
// uint256 daysAfterStaking = daysStaked - stakingDays;
// uint256 payOutAmount =
// amountAndInterest.mul(uint256(714).sub(daysAfterStaking)).div(
// 700
// );
// uint256 lateUnstakePenalty = amountAndInterest.sub(payOutAmount);
// return (payOutAmount, lateUnstakePenalty);
// Nothing
} else {
return (0, amountAndInterest);
}
}
//makePayout function runs once per day and takes all the AXN earned as interest and puts it into payout array for the day
function makePayout() public {
require(now >= nextPayoutCall, 'Staking: Wrong payout time');
uint256 payout = _getPayout();
payouts.push(
Payout({payout: payout, sharesTotalSupply: sharesTotalSupply})
);
nextPayoutCall = nextPayoutCall.add(stepTimestamp);
//call updateShareRate once a day as sharerate increases based on the daily Payout amount
updateShareRate(payout);
emit MakePayout(payout, sharesTotalSupply, now);
}
function _getPayout() internal returns (uint256) {
//amountTokenInDay - AXN from auction buybacks goes into the staking contract
uint256 amountTokenInDay =
IERC20Upgradeable(addresses.mainToken).balanceOf(address(this));
IERC20Upgradeable(addresses.mainToken).transfer(
0x000000000000000000000000000000000000dEaD,
amountTokenInDay
); // Send to dead address
uint256 balanceOfDead =
IERC20Upgradeable(addresses.mainToken).balanceOf(
0x000000000000000000000000000000000000dEaD
);
uint256 currentTokenTotalSupply =
(IERC20Upgradeable(addresses.mainToken).totalSupply());
//we add 8% inflation
uint256 inflation =
uint256(8)
.mul(
currentTokenTotalSupply.sub(balanceOfDead).add(
totalStakedAmount
)
)
.div(36500);
emit DailyBurn(amountTokenInDay, currentTokenTotalSupply, now);
return inflation;
}
// formula for shares calculation given a number of AXN and a start and end date
// @param amount {uint256} - amount of AXN
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
function _getStakersSharesAmount(
uint256 amount,
uint256 start,
uint256 end
) internal view returns (uint256) {
uint256 stakingDays = (end.sub(start)).div(stepTimestamp);
uint256 numerator = amount.mul(uint256(1819).add(stakingDays));
uint256 denominator = uint256(1820).mul(shareRate);
return (numerator).mul(1e18).div(denominator);
}
// @param amount {uint256} - amount of AXN
// @param shares {uint256} - number of shares
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
// @param stakingInterest {uint256} - interest earned by the stake
function _getShareRate(
uint256 amount,
uint256 shares,
uint256 start,
uint256 end,
uint256 stakingInterest
) internal view returns (uint256) {
uint256 stakingDays = (end.sub(start)).div(stepTimestamp);
uint256 numerator =
(amount.add(stakingInterest)).mul(uint256(1819).add(stakingDays));
uint256 denominator = uint256(1820).mul(shares);
return (numerator).mul(1e18).div(denominator);
}
//takes a matures stake and allows restake instead of having to withdraw the axn and stake it back into another stake
//restake will take the principal + interest earned + allow a topup
// @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restake(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares != 0 && session.withdrawn == false,
'Staking: Stake withdrawn/invalid'
);
uint256 actualEnd = now;
require(session.end <= actualEnd, 'Staking: Stake not mature');
uint256 amountOut = unstakeInternal(session, sessionId, actualEnd);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
//same as restake but for layer 1 stakes
// @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restakeV1(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(sessionId <= lastSessionIdV1, 'Staking: Invalid sessionId');
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares == 0 && session.withdrawn == false,
'Staking: Stake withdrawn'
);
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(msg.sender, sessionId);
// Unstaked in v1 / doesn't exist
require(shares != 0, 'Staking: Stake withdrawn');
uint256 actualEnd = now;
require(end <= actualEnd, 'Staking: Stake not mature');
uint256 sessionStakingDays = (end - start) / stepTimestamp;
uint256 lastPayout = sessionStakingDays + firstPayout;
uint256 amountOut =
unstakeV1Internal(
sessionId,
amount,
start,
end,
actualEnd,
shares,
firstPayout,
lastPayout
);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
// @param session {Session} - session of the stake
// @param sessionId {uint256} - id of the stake
// @param actualEnd {uint256} - the date when the stake was actually been unstaked
function unstakeInternal(
Session storage session,
uint256 sessionId,
uint256 actualEnd
) internal returns (uint256) {
uint256 amountOut =
unstakeInternalCommon(
sessionId,
session.amount,
session.start,
session.end,
actualEnd,
session.shares,
session.firstPayout,
session.lastPayout
);
session.end = actualEnd;
session.withdrawn = true;
session.payout = amountOut;
return amountOut;
}
// @param sessionID {uint256} - id of the stake
// @param amount {uint256} - amount of AXN
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
// @param actualEnd {uint256} - actual end date of the stake
// @param shares {uint256} - number of stares of the stake
// @param firstPayout {uint256} - id of the first payout for the stake
// @param lastPayout {uint256} - if of the last payout for the stake
// @param stakingDays {uint256} - number of staking days
function unstakeV1Internal(
uint256 sessionId,
uint256 amount,
uint256 start,
uint256 end,
uint256 actualEnd,
uint256 shares,
uint256 firstPayout,
uint256 lastPayout
) internal returns (uint256) {
uint256 amountOut =
unstakeInternalCommon(
sessionId,
amount,
start,
end,
actualEnd,
shares,
firstPayout,
lastPayout
);
sessionDataOf[msg.sender][sessionId] = Session({
amount: amount,
start: start,
end: actualEnd,
shares: shares,
firstPayout: firstPayout,
lastPayout: lastPayout,
withdrawn: true,
payout: amountOut
});
sessionsOf[msg.sender].push(sessionId);
return amountOut;
}
// @param sessionID {uint256} - id of the stake
// @param amount {uint256} - amount of AXN
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
// @param actualEnd {uint256} - actual end date of the stake
// @param shares {uint256} - number of stares of the stake
// @param firstPayout {uint256} - id of the first payout for the stake
// @param lastPayout {uint256} - if of the last payout for the stake
function unstakeInternalCommon(
uint256 sessionId,
uint256 amount,
uint256 start,
uint256 end,
uint256 actualEnd,
uint256 shares,
uint256 firstPayout,
uint256 lastPayout
) internal returns (uint256) {
if (now >= nextPayoutCall) makePayout();
if (isVcaRegistered[msg.sender] == false)
setTotalSharesOfAccountInternal(msg.sender);
uint256 stakingInterest =
calculateStakingInterest(firstPayout, lastPayout, shares);
sharesTotalSupply = sharesTotalSupply.sub(shares);
totalStakedAmount = totalStakedAmount.sub(amount);
totalVcaRegisteredShares = totalVcaRegisteredShares.sub(shares);
uint256 oldTotalSharesOf = totalSharesOf[msg.sender];
totalSharesOf[msg.sender] = totalSharesOf[msg.sender].sub(shares);
rebalance(msg.sender, oldTotalSharesOf);
(uint256 amountOut, uint256 penalty) =
getAmountOutAndPenalty(amount, start, end, stakingInterest);
// add bpd to amount amountOut if stakingDays >= basePeriod
uint256 stakingDays = (actualEnd - start) / stepTimestamp;
if (stakingDays >= basePeriod) {
// We use "Actual end" so that if a user tries to withdraw their BPD early they don't get the shares
uint256 bpdAmount =
calcBPD(start, actualEnd < end ? actualEnd : end, shares);
amountOut = amountOut.add(bpdAmount);
}
// To auction
// if (penalty != 0) {
// _initPayout(addresses.auction, penalty);
// IAuction(addresses.auction).callIncomeDailyTokensTrigger(penalty);
// }
emit Unstake(
msg.sender,
sessionId,
amountOut,
start,
actualEnd,
shares
);
return amountOut;
}
// @param sessionID {uint256} - id of the stake
// @param amount {uint256} - amount of AXN
// @param start {uint256} - start date of the stake
// @param end {uint256} - end date of the stake
// @param stakingDays {uint256} - number of staking days
// @param firstPayout {uint256} - id of the first payout for the stake
// @param lastPayout {uint256} - if of the last payout for the stake
// @param staker {address} - address of the staker account
function stakeInternalCommon(
uint256 sessionId,
uint256 amount,
uint256 start,
uint256 end,
uint256 stakingDays,
uint256 firstPayout,
address staker
) internal {
uint256 shares = _getStakersSharesAmount(amount, start, end);
sharesTotalSupply = sharesTotalSupply.add(shares);
totalStakedAmount = totalStakedAmount.add(amount);
totalVcaRegisteredShares = totalVcaRegisteredShares.add(shares);
uint256 oldTotalSharesOf = totalSharesOf[staker];
totalSharesOf[staker] = totalSharesOf[staker].add(shares);
rebalance(staker, oldTotalSharesOf);
sessionDataOf[staker][sessionId] = Session({
amount: amount,
start: start,
end: end,
shares: shares,
firstPayout: firstPayout,
lastPayout: firstPayout + stakingDays,
withdrawn: false,
payout: 0
});
sessionsOf[staker].push(sessionId);
// add shares to bpd pool
addBPDShares(shares, start, end);
emit Stake(staker, sessionId, amount, start, end, shares);
}
//function to withdraw the dividends earned for a specific token
// @param tokenAddress {address} - address of the dividend token
function withdrawDivToken(address tokenAddress) external {
withdrawDivTokenInternal(tokenAddress, totalSharesOf[msg.sender]);
}
function withdrawDivTokenInternal(
address tokenAddress,
uint256 _totalSharesOf
) internal {
uint256 tokenInterestEarned =
getTokenInterestEarnedInternal(
msg.sender,
tokenAddress,
_totalSharesOf
);
// after dividents are paid we need to set the deductBalance of that token to current token price * total shares of the account
deductBalances[msg.sender][tokenAddress] = totalSharesOf[msg.sender]
.mul(tokenPricePerShare[tokenAddress]);
/** 0xFF... is our ethereum placeholder address */
if (
tokenAddress != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)
) {
IERC20Upgradeable(tokenAddress).transfer(
msg.sender,
tokenInterestEarned
);
} else {
msg.sender.transfer(tokenInterestEarned);
}
emit WithdrawLiquidDiv(msg.sender, tokenAddress, tokenInterestEarned);
}
//calculate the interest earned by an address for a specific dividend token
// @param accountAddress {address} - address of account
// @param tokenAddress {address} - address of the dividend token
function getTokenInterestEarned(
address accountAddress,
address tokenAddress
) external view returns (uint256) {
return
getTokenInterestEarnedInternal(
accountAddress,
tokenAddress,
totalSharesOf[accountAddress]
);
}
// @param accountAddress {address} - address of account
// @param tokenAddress {address} - address of the dividend token
function getTokenInterestEarnedInternal(
address accountAddress,
address tokenAddress,
uint256 _totalSharesOf
) internal view returns (uint256) {
return
_totalSharesOf
.mul(tokenPricePerShare[tokenAddress])
.sub(deductBalances[accountAddress][tokenAddress])
.div(10**36); //we divide since we multiplied the price by 10**36 for precision
}
//the rebalance function recalculates the deductBalances of an user after the total number of shares changes as a result of a stake/unstake
// @param staker {address} - address of account
// @param oldTotalSharesOf {uint256} - previous number of shares for the account
function rebalance(address staker, uint256 oldTotalSharesOf) internal {
for (uint8 i = 0; i < divTokens.length(); i++) {
uint256 tokenInterestEarned =
oldTotalSharesOf.mul(tokenPricePerShare[divTokens.at(i)]).sub(
deductBalances[staker][divTokens.at(i)]
);
if (
totalSharesOf[staker].mul(tokenPricePerShare[divTokens.at(i)]) <
tokenInterestEarned
) {
withdrawDivTokenInternal(divTokens.at(i), oldTotalSharesOf);
} else {
deductBalances[staker][divTokens.at(i)] = totalSharesOf[staker]
.mul(tokenPricePerShare[divTokens.at(i)])
.sub(tokenInterestEarned);
}
}
}
//registration function that sets the total number of shares for an account and inits the deductBalances
// @param account {address} - address of account
function setTotalSharesOfAccountInternal(address account)
internal
pausable
{
require(
isVcaRegistered[account] == false ||
hasRole(MIGRATOR_ROLE, msg.sender),
'STAKING: Account already registered.'
);
uint256 totalShares;
//pull the layer 2 staking sessions for the account
uint256[] storage sessionsOfAccount = sessionsOf[account];
for (uint256 i = 0; i < sessionsOfAccount.length; i++) {
if (sessionDataOf[account][sessionsOfAccount[i]].withdrawn)
//make sure the stake is active; not withdrawn
continue;
totalShares = totalShares.add( //sum total shares
sessionDataOf[account][sessionsOfAccount[i]].shares
);
}
//pull stakes from layer 1
uint256[] memory v1SessionsOfAccount = stakingV1.sessionsOf_(account);
for (uint256 i = 0; i < v1SessionsOfAccount.length; i++) {
if (sessionDataOf[account][v1SessionsOfAccount[i]].shares != 0)
//make sure the stake was not withdran.
continue;
if (v1SessionsOfAccount[i] > lastSessionIdV1) continue; //make sure we only take layer 1 stakes in consideration
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(account, v1SessionsOfAccount[i]);
(amount);
(start);
(end);
(firstPayout);
if (shares == 0) continue;
totalShares = totalShares.add(shares); //calclate total shares
}
isVcaRegistered[account] = true; //confirm the registration was completed
if (totalShares != 0) {
totalSharesOf[account] = totalShares;
totalVcaRegisteredShares = totalVcaRegisteredShares.add( //update the global total number of VCA registered shares
totalShares
);
//init deductBalances with the present values
for (uint256 i = 0; i < divTokens.length(); i++) {
deductBalances[account][divTokens.at(i)] = totalShares.mul(
tokenPricePerShare[divTokens.at(i)]
);
}
}
emit AccountRegistered(account, totalShares);
}
//function to allow anyone to call the registration of another address
// @param _address {address} - address of account
function setTotalSharesOfAccount(address _address) external {
setTotalSharesOfAccountInternal(_address);
}
//function that will update the price per share for a dividend token. it is called from within the auction contract as a result of a venture auction bid
// @param bidderAddress {address} - the address of the bidder
// @param originAddress {address} - the address of origin/dev fee
// @param tokenAddress {address} - the divident token address
// @param amountBought {uint256} - the amount in ETH that was bid in the auction
function updateTokenPricePerShare(
address payable bidderAddress,
address payable originAddress,
address tokenAddress,
uint256 amountBought
) external payable override onlyExternalStaker {
if (tokenAddress != addresses.mainToken) {
tokenPricePerShare[tokenAddress] = tokenPricePerShare[tokenAddress]
.add(amountBought.mul(10**36).div(totalVcaRegisteredShares)); //increase the token price per share with the amount bought divided by the total Vca registered shares
}
}
//add a new dividend token
// @param tokenAddress {address} - dividend token address
function addDivToken(address tokenAddress)
external
override
onlyExternalStaker
{
if (
!divTokens.contains(tokenAddress) &&
tokenAddress != addresses.mainToken
) {
//make sure the token is not already added
divTokens.add(tokenAddress);
}
}
//function to increase the share rate price
//the update happens daily and used the amount of AXN sold through regular auction to calculate the amount to increase the share rate with
// @param _payout {uint256} - amount of AXN that was bought back through the regular auction
function updateShareRate(uint256 _payout) internal {
uint256 currentTokenTotalSupply =
IERC20Upgradeable(addresses.mainToken).totalSupply();
uint256 growthFactor =
_payout.mul(1e18).div(
currentTokenTotalSupply + totalStakedAmount + 1 //we calculate the total AXN supply as circulating + staked
);
if (shareRateScalingFactor == 0) {
//use a shareRateScalingFactor which can be set in order to tune the speed of shareRate increase
shareRateScalingFactor = 1;
}
shareRate = shareRate
.mul(1e18 + shareRateScalingFactor.mul(growthFactor)) //1e18 used for precision.
.div(1e18);
}
//function to set the shareRateScalingFactor
// @param _scalingFactor {uint256} - scaling factor number
function setShareRateScalingFactor(uint256 _scalingFactor)
external
onlyManager
{
shareRateScalingFactor = _scalingFactor;
}
//function that allows a stake to be upgraded to a stake with a length of 5555 days without incuring any penalties
//the function takes the current earned interest and uses the principal + interest to create a new stake
//for v2 stakes it's only updating the current existing stake info, it's not creating a new stake
// @param sessionId {uint256} - id of the staking session
function maxShare(uint256 sessionId) external pausable {
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares != 0 && session.withdrawn == false,
'STAKING: Stake withdrawn or not set'
);
(
uint256 newStart,
uint256 newEnd,
uint256 newAmount,
uint256 newShares
) =
maxShareUpgrade(
session.firstPayout,
session.lastPayout,
session.shares,
session.amount
);
addBPDMaxShares(
session.shares,
session.start,
session.end,
newShares,
newStart,
newEnd
);
maxShareInternal(
sessionId,
session.shares,
newShares,
session.amount,
newAmount,
newStart,
newEnd
);
sessionDataOf[msg.sender][sessionId].amount = newAmount;
sessionDataOf[msg.sender][sessionId].end = newEnd;
sessionDataOf[msg.sender][sessionId].start = newStart;
sessionDataOf[msg.sender][sessionId].shares = newShares;
sessionDataOf[msg.sender][sessionId].firstPayout = payouts.length;
sessionDataOf[msg.sender][sessionId].lastPayout = payouts.length + 5555;
}
//similar to the maxShare function, but for layer 1 stakes only
// @param sessionId {uint256} - id of the staking session
function maxShareV1(uint256 sessionId) external pausable {
require(sessionId <= lastSessionIdV1, 'STAKING: Invalid sessionId');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares == 0 && session.withdrawn == false,
'STAKING: Stake withdrawn'
);
(
uint256 amount,
uint256 start,
uint256 end,
uint256 shares,
uint256 firstPayout
) = stakingV1.sessionDataOf(msg.sender, sessionId);
require(shares != 0, 'STAKING: Stake withdrawn v1');
uint256 stakingDays = (end - start) / stepTimestamp;
uint256 lastPayout = stakingDays + firstPayout;
(
uint256 newStart,
uint256 newEnd,
uint256 newAmount,
uint256 newShares
) = maxShareUpgrade(firstPayout, lastPayout, shares, amount);
addBPDMaxShares(shares, start, end, newShares, newStart, newEnd);
maxShareInternal(
sessionId,
shares,
newShares,
amount,
newAmount,
newStart,
newEnd
);
sessionDataOf[msg.sender][sessionId] = Session({
amount: newAmount,
start: newStart,
end: newEnd,
shares: newShares,
firstPayout: payouts.length,
lastPayout: payouts.length + 5555,
withdrawn: false,
payout: 0
});
sessionsOf[msg.sender].push(sessionId);
}
//function to calculate the new start, end, new amount and new shares for a max share upgrade
// @param firstPayout {uint256} - id of the first Payout
// @param lasttPayout {uint256} - id of the last Payout
// @param shares {uint256} - number of shares
// @param amount {uint256} - amount of AXN
function maxShareUpgrade(
uint256 firstPayout,
uint256 lastPayout,
uint256 shares,
uint256 amount
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
require(
maxShareEventActive == true,
'STAKING: Max Share event is not active'
);
require(
lastPayout - firstPayout <= maxShareMaxDays,
'STAKING: Max Share Upgrade - Stake must be less then max share max days'
);
uint256 stakingInterest =
calculateStakingInterest(firstPayout, lastPayout, shares);
uint256 newStart = now;
uint256 newEnd = newStart + (stepTimestamp * 5555);
uint256 newAmount = stakingInterest + amount;
uint256 newShares =
_getStakersSharesAmount(newAmount, newStart, newEnd);
require(
newShares > shares,
'STAKING: New shares are not greater then previous shares'
);
return (newStart, newEnd, newAmount, newShares);
}
// @param sessionId {uint256} - id of the staking session
// @param oldShares {uint256} - previous number of shares
// @param newShares {uint256} - new number of shares
// @param oldAmount {uint256} - old amount of AXN
// @param newAmount {uint256} - new amount of AXN
// @param newStart {uint256} - new start date for the stake
// @param newEnd {uint256} - new end date for the stake
function maxShareInternal(
uint256 sessionId,
uint256 oldShares,
uint256 newShares,
uint256 oldAmount,
uint256 newAmount,
uint256 newStart,
uint256 newEnd
) internal {
if (now >= nextPayoutCall) makePayout();
if (isVcaRegistered[msg.sender] == false)
setTotalSharesOfAccountInternal(msg.sender);
sharesTotalSupply = sharesTotalSupply.add(newShares - oldShares);
totalStakedAmount = totalStakedAmount.add(newAmount - oldAmount);
totalVcaRegisteredShares = totalVcaRegisteredShares.add(
newShares - oldShares
);
uint256 oldTotalSharesOf = totalSharesOf[msg.sender];
totalSharesOf[msg.sender] = totalSharesOf[msg.sender].add(
newShares - oldShares
);
rebalance(msg.sender, oldTotalSharesOf);
emit MaxShareUpgrade(
msg.sender,
sessionId,
oldAmount,
newAmount,
oldShares,
newShares,
newStart,
newEnd
);
}
// stepTimestamp
// startContract
function calculateStepsFromStart() public view returns (uint256) {
return now.sub(startContract).div(stepTimestamp);
}
/** Set Max Shares */
function setMaxShareEventActive(bool _active) external onlyManager {
maxShareEventActive = _active;
}
function getMaxShareEventActive() external view returns (bool) {
return maxShareEventActive;
}
function setMaxShareMaxDays(uint16 _maxShareMaxDays) external onlyManager {
maxShareMaxDays = _maxShareMaxDays;
}
function setTotalVcaRegisteredShares(uint256 _shares)
external
onlyMigrator
{
totalVcaRegisteredShares = _shares;
}
function setPaused(bool _paused) external {
require(
hasRole(MIGRATOR_ROLE, msg.sender) ||
hasRole(MANAGER_ROLE, msg.sender),
'STAKING: User must be manager or migrator'
);
paused = _paused;
}
function getPaused() external view returns (bool) {
return paused;
}
function getMaxShareMaxDays() external view returns (uint16) {
return maxShareMaxDays;
}
/** Roles management - only for multi sig address */
function setupRole(bytes32 role, address account) external onlyManager {
_setupRole(role, account);
}
function getDivTokens() external view returns (address[] memory) {
address[] memory divTokenAddresses = new address[](divTokens.length());
for (uint8 i = 0; i < divTokens.length(); i++) {
divTokenAddresses[i] = divTokens.at(i);
}
return divTokenAddresses;
}
function getTotalSharesOf(address account) external view returns (uint256) {
return totalSharesOf[account];
}
function getTotalVcaRegisteredShares() external view returns (uint256) {
return totalVcaRegisteredShares;
}
function getIsVCARegistered(address staker) external view returns (bool) {
return isVcaRegistered[staker];
}
function setBPDPools(
uint128[5] calldata poolAmount,
uint128[5] calldata poolShares
) external onlyMigrator {
for (uint8 i = 0; i < poolAmount.length; i++) {
bpd128.pool[i] = poolAmount[i];
bpd128.shares[i] = poolShares[i];
}
}
function findBPDEligible(uint256 starttime, uint256 endtime)
external
view
returns (uint16[2] memory)
{
return findBPDs(starttime, endtime);
}
function findBPDs(uint256 starttime, uint256 endtime)
internal
view
returns (uint16[2] memory)
{
uint16[2] memory bpdInterval;
uint256 denom = stepTimestamp.mul(350);
bpdInterval[0] = uint16(
MathUpgradeable.min(5, starttime.sub(startContract).div(denom))
); // (starttime - t0) // 350
uint256 bpdEnd =
uint256(bpdInterval[0]) + endtime.sub(starttime).div(denom);
bpdInterval[1] = uint16(MathUpgradeable.min(bpdEnd, 5)); // bpd_first + nx350
return bpdInterval;
}
function addBPDMaxShares(
uint256 oldShares,
uint256 oldStart,
uint256 oldEnd,
uint256 newShares,
uint256 newStart,
uint256 newEnd
) internal {
uint16[2] memory oldBpdInterval = findBPDs(oldStart, oldEnd);
uint16[2] memory newBpdInterval = findBPDs(newStart, newEnd);
for (uint16 i = oldBpdInterval[0]; i < newBpdInterval[1]; i++) {
uint256 shares = newShares;
if (oldBpdInterval[1] > i) {
shares = shares.sub(oldShares);
}
bpd128.shares[i] += uint128(shares); // we only do integer shares, no decimals
}
}
function addBPDShares(
uint256 shares,
uint256 starttime,
uint256 endtime
) internal {
uint16[2] memory bpdInterval = findBPDs(starttime, endtime);
for (uint16 i = bpdInterval[0]; i < bpdInterval[1]; i++) {
bpd128.shares[i] += uint128(shares); // we only do integer shares, no decimals
}
}
function calcBPDOnWithdraw(uint256 shares, uint16[2] memory bpdInterval)
internal
view
returns (uint256)
{
uint256 bpdAmount;
uint256 shares1e18 = shares.mul(1e18);
for (uint16 i = bpdInterval[0]; i < bpdInterval[1]; i++) {
bpdAmount += shares1e18.div(bpd128.shares[i]).mul(bpd128.pool[i]);
}
return bpdAmount.div(1e18);
}
/** CalcBPD
@param start - Start of the stake
@param end - ACTUAL End of the stake. We want to calculate using the actual end. We'll use findBPD's to figure out what BPD's the user is eligible for
@param shares - Shares of stake
*/
function calcBPD(
uint256 start,
uint256 end,
uint256 shares
) public view returns (uint256) {
uint16[2] memory bpdInterval = findBPDs(start, end);
return calcBPDOnWithdraw(shares, bpdInterval);
}
function getBPD()
external
view
returns (uint128[5] memory, uint128[5] memory)
{
return (bpd128.pool, bpd128.shares);
}
function getDeductBalances(address account, address token)
external
view
returns (uint256)
{
return deductBalances[account][token];
}
function getTokenPricePerShare(address token)
external
view
returns (uint256)
{
return tokenPricePerShare[token];
}
function recover(
address recoverFor,
address tokenToRecover,
uint256 amount
) external onlyMigrator {
IERC20Upgradeable(tokenToRecover).transfer(recoverFor, amount);
}
function safeRecover(
address recoverFor,
address tokenToRecover,
uint256 amount
) external onlyMigrator {
IERC20Upgradeable(tokenToRecover).safeTransfer(recoverFor, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IToken {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IAuction {
function callIncomeDailyTokensTrigger(uint256 amount) external;
function callIncomeWeeklyTokensTrigger(uint256 amount) external;
function addReservesToAuction(uint256 daysInFuture, uint256 amount) external returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IStaking {
function externalStake(
uint256 amount,
uint256 stakingDays,
address staker
) external;
function updateTokenPricePerShare(
address payable bidderAddress,
address payable originAddress,
address tokenAddress,
uint256 amountBought
) external payable;
function addDivToken(address tokenAddress) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IStakingV1 {
function sessionDataOf(address, uint256)
external view returns (uint256, uint256, uint256, uint256, uint256);
function sessionsOf_(address)
external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
| accountAddress {address} - address of account tokenAddress {address} - address of the dividend token | function getTokenInterestEarnedInternal(
address accountAddress,
address tokenAddress,
uint256 _totalSharesOf
) internal view returns (uint256) {
return
_totalSharesOf
.mul(tokenPricePerShare[tokenAddress])
.sub(deductBalances[accountAddress][tokenAddress])
}
| 6,025,777 |
pragma solidity ^0.4.4;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
// Standard token interface (ERC 20)
// https://github.com/ethereum/EIPs/issues/20
contract Token is SafeMath {
// Functions:
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
function transfer(address _to, uint256 _value) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value){}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
// Events:
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StdToken is Token {
// Fields:
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public totalSupply = 0;
// Functions:
function transfer(address _to, uint256 _value) {
if((balances[msg.sender] < _value) || (balances[_to] + _value <= balances[_to])) {
throw;
}
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) {
if((balances[_from] < _value) ||
(allowed[_from][msg.sender] < _value) ||
(balances[_to] + _value <= balances[_to]))
{
throw;
}
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
modifier onlyPayloadSize(uint _size) {
if(msg.data.length < _size + 4) {
throw;
}
_;
}
}
contract MNTP is StdToken {
/// Fields:
string public constant name = "Goldmint MNT Prelaunch Token";
string public constant symbol = "MNTP";
uint public constant decimals = 18;
address public creator = 0x0;
address public icoContractAddress = 0x0;
bool public lockTransfers = false;
// 10 mln
uint public constant TOTAL_TOKEN_SUPPLY = 10000000 * (1 ether / 1 wei);
/// Modifiers:
modifier onlyCreator() { if(msg.sender != creator) throw; _; }
modifier byCreatorOrIcoContract() { if((msg.sender != creator) && (msg.sender != icoContractAddress)) throw; _; }
function setCreator(address _creator) onlyCreator {
creator = _creator;
}
/// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
/// Functions:
/// @dev Constructor
function MNTP() {
creator = msg.sender;
// 10 mln tokens total
assert(TOTAL_TOKEN_SUPPLY == (10000000 * (1 ether / 1 wei)));
}
/// @dev Override
function transfer(address _to, uint256 _value) public {
if(lockTransfers){
throw;
}
super.transfer(_to,_value);
}
/// @dev Override
function transferFrom(address _from, address _to, uint256 _value)public{
if(lockTransfers){
throw;
}
super.transferFrom(_from,_to,_value);
}
function issueTokens(address _who, uint _tokens) byCreatorOrIcoContract {
if((totalSupply + _tokens) > TOTAL_TOKEN_SUPPLY){
throw;
}
balances[_who] += _tokens;
totalSupply += _tokens;
}
function burnTokens(address _who, uint _tokens) byCreatorOrIcoContract {
balances[_who] = safeSub(balances[_who], _tokens);
totalSupply = safeSub(totalSupply, _tokens);
}
function lockTransfer(bool _lock) byCreatorOrIcoContract {
lockTransfers = _lock;
}
// Do not allow to send money directly to this contract
function() {
throw;
}
}
// This contract will hold all tokens that were unsold during ICO
// (Goldmint should be able to withdraw them and sold only 1 year post-ICO)
contract GoldmintUnsold is SafeMath {
address public creator;
address public teamAccountAddress;
address public icoContractAddress;
uint64 public icoIsFinishedDate;
MNTP public mntToken;
function GoldmintUnsold(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
mntToken = MNTP(_mntTokenAddress);
}
/// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) {
if(msg.sender!=creator){
throw;
}
icoContractAddress = _icoContractAddress;
}
function icoIsFinished() public {
// only by Goldmint contract
if(msg.sender!=icoContractAddress){
throw;
}
icoIsFinishedDate = uint64(now);
}
// can be called by anyone...
function withdrawTokens() public {
// wait for 1 year!
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
if(uint(now) < oneYearPassed) throw;
// transfer all tokens from this contract to the teamAccountAddress
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
// Default fallback function
function() payable {
throw;
}
}
contract FoundersVesting is SafeMath {
address public creator;
address public teamAccountAddress;
uint64 public lastWithdrawTime;
uint public withdrawsCount = 0;
uint public amountToSend = 0;
MNTP public mntToken;
function FoundersVesting(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
lastWithdrawTime = uint64(now);
mntToken = MNTP(_mntTokenAddress);
}
// can be called by anyone...
function withdrawTokens() public {
// 1 - wait for next month!
uint64 oneMonth = lastWithdrawTime + 30 days;
if(uint(now) < oneMonth) throw;
// 2 - calculate amount (only first time)
if(withdrawsCount==0){
amountToSend = mntToken.balanceOf(this) / 10;
}
// 3 - send 1/10th
assert(amountToSend!=0);
mntToken.transfer(teamAccountAddress,amountToSend);
withdrawsCount++;
lastWithdrawTime = uint64(now);
}
// Default fallback function
function() payable {
throw;
}
}
contract Goldmint is SafeMath {
address public creator = 0x0;
address public tokenManager = 0x0;
address public multisigAddress = 0x0;
address public otherCurrenciesChecker = 0x0;
uint64 public icoStartedTime = 0;
MNTP public mntToken;
GoldmintUnsold public unsoldContract;
// These can be changed before ICO start ($7USD/MNTP)
uint constant STD_PRICE_USD_PER_1000_TOKENS = 7000;
// coinmarketcap.com 14.08.2017
uint constant ETH_PRICE_IN_USD = 300;
// price changes from block to block
//uint public constant SINGLE_BLOCK_LEN = 700000;
uint public constant SINGLE_BLOCK_LEN = 100;
///////
// 1 000 000 tokens
uint public constant BONUS_REWARD = 1000000 * (1 ether/ 1 wei);
// 2 000 000 tokens
uint public constant FOUNDERS_REWARD = 2000000 * (1 ether / 1 wei);
// 7 000 000 we sell only this amount of tokens during the ICO
//uint public constant ICO_TOKEN_SUPPLY_LIMIT = 7000000 * (1 ether / 1 wei);
uint public constant ICO_TOKEN_SUPPLY_LIMIT = 250 * (1 ether / 1 wei);
// this is total number of tokens sold during ICO
uint public icoTokensSold = 0;
// this is total number of tokens sent to GoldmintUnsold contract after ICO is finished
uint public icoTokensUnsold = 0;
// this is total number of tokens that were issued by a scripts
uint public issuedExternallyTokens = 0;
bool public foundersRewardsMinted = false;
bool public restTokensMoved = false;
// this is where FOUNDERS_REWARD will be allocated
address public foundersRewardsAccount = 0x0;
enum State{
Init,
ICORunning,
ICOPaused,
ICOFinished
}
State public currentState = State.Init;
/// Modifiers:
modifier onlyCreator() { if(msg.sender != creator) throw; _; }
modifier onlyTokenManager() { if(msg.sender != tokenManager) throw; _; }
modifier onlyOtherCurrenciesChecker() { if(msg.sender != otherCurrenciesChecker) throw; _; }
modifier onlyInState(State state){ if(state != currentState) throw; _; }
/// Events:
event LogStateSwitch(State newState);
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
/// Functions:
/// @dev Constructor
function Goldmint(
address _multisigAddress,
address _tokenManager,
address _otherCurrenciesChecker,
address _mntTokenAddress,
address _unsoldContractAddress,
address _foundersVestingAddress)
{
creator = msg.sender;
multisigAddress = _multisigAddress;
tokenManager = _tokenManager;
otherCurrenciesChecker = _otherCurrenciesChecker;
mntToken = MNTP(_mntTokenAddress);
unsoldContract = GoldmintUnsold(_unsoldContractAddress);
// slight rename
foundersRewardsAccount = _foundersVestingAddress;
}
/// @dev This function is automatically called when ICO is started
/// WARNING: can be called multiple times!
function startICO() internal onlyCreator {
mintFoundersRewards(foundersRewardsAccount);
mntToken.lockTransfer(true);
if(icoStartedTime==0){
icoStartedTime = uint64(now);
}
}
function pauseICO() internal onlyCreator {
mntToken.lockTransfer(false);
}
/// @dev This function is automatically called when ICO is finished
/// WARNING: can be called multiple times!
function finishICO() internal {
mntToken.lockTransfer(false);
if(!restTokensMoved){
restTokensMoved = true;
// move all unsold tokens to unsoldTokens contract
icoTokensUnsold = safeSub(ICO_TOKEN_SUPPLY_LIMIT,icoTokensSold);
if(icoTokensUnsold>0){
mntToken.issueTokens(unsoldContract,icoTokensUnsold);
unsoldContract.icoIsFinished();
}
}
// send all ETH to multisig
if(this.balance>0){
if(!multisigAddress.send(this.balance)) throw;
}
}
function mintFoundersRewards(address _whereToMint) internal onlyCreator {
if(!foundersRewardsMinted){
foundersRewardsMinted = true;
mntToken.issueTokens(_whereToMint,FOUNDERS_REWARD);
}
}
/// Access methods:
function setTokenManager(address _new) public onlyTokenManager {
tokenManager = _new;
}
function setOtherCurrenciesChecker(address _new) public onlyOtherCurrenciesChecker {
otherCurrenciesChecker = _new;
}
function getTokensIcoSold() constant public returns (uint){
return icoTokensSold;
}
function getTotalIcoTokens() constant public returns (uint){
return ICO_TOKEN_SUPPLY_LIMIT;
}
function getMntTokenBalance(address _of) constant public returns (uint){
return mntToken.balanceOf(_of);
}
function getCurrentPrice()constant public returns (uint){
return getMntTokensPerEth(icoTokensSold);
}
function getBlockLength()constant public returns (uint){
return SINGLE_BLOCK_LEN;
}
////
function isIcoFinished() public returns(bool){
if(icoStartedTime==0){return false;}
// 1 - if time elapsed
uint64 oneMonth = icoStartedTime + 30 days;
if(uint(now) > oneMonth){return true;}
// 2 - if all tokens are sold
if(icoTokensSold>=ICO_TOKEN_SUPPLY_LIMIT){
return true;
}
return false;
}
function setState(State _nextState) public {
// only creator can change state
// but in case ICOFinished -> anyone can do that after all time is elapsed
bool icoShouldBeFinished = isIcoFinished();
if((msg.sender!=creator) && !(icoShouldBeFinished && State.ICOFinished==_nextState)){
throw;
}
bool canSwitchState
= (currentState == State.Init && _nextState == State.ICORunning)
|| (currentState == State.ICORunning && _nextState == State.ICOPaused)
|| (currentState == State.ICOPaused && _nextState == State.ICORunning)
|| (currentState == State.ICORunning && _nextState == State.ICOFinished)
|| (currentState == State.ICOFinished && _nextState == State.ICORunning);
if(!canSwitchState) throw;
currentState = _nextState;
LogStateSwitch(_nextState);
if(currentState==State.ICORunning){
startICO();
}else if(currentState==State.ICOFinished){
finishICO();
}else if(currentState==State.ICOPaused){
pauseICO();
}
}
function getMntTokensPerEth(uint tokensSold) public constant returns (uint){
// 10 buckets
uint priceIndex = (tokensSold / (1 ether/ 1 wei)) / SINGLE_BLOCK_LEN;
assert(priceIndex>=0 && (priceIndex<=9));
uint8[10] memory discountPercents = [20,15,10,8,6,4,2,0,0,0];
// We have to multiply by '1 ether' to avoid float truncations
// Example: ($7000 * 100) / 120 = $5833.33333
uint pricePer1000tokensUsd =
((STD_PRICE_USD_PER_1000_TOKENS * 100) * (1 ether / 1 wei)) / (100 + discountPercents[priceIndex]);
// Correct: 300000 / 5833.33333333 = 51.42857142
// We have to multiply by '1 ether' to avoid float truncations
uint mntPerEth = (ETH_PRICE_IN_USD * 1000 * (1 ether / 1 wei) * (1 ether / 1 wei)) / pricePer1000tokensUsd;
return mntPerEth;
}
function buyTokens(address _buyer) public payable onlyInState(State.ICORunning) {
if(msg.value == 0) throw;
// The price is selected based on current sold tokens.
// Price can 'overlap'. For example:
// 1. if currently we sold 699950 tokens (the price is 10% discount)
// 2. buyer buys 1000 tokens
// 3. the price of all 1000 tokens would be with 10% discount!!!
uint newTokens = (msg.value * getMntTokensPerEth(icoTokensSold)) / (1 ether / 1 wei);
issueTokensInternal(_buyer,newTokens);
}
/// @dev This is called by other currency processors to issue new tokens
function issueTokensFromOtherCurrency(address _to, uint _wei_count) onlyInState(State.ICORunning) public onlyOtherCurrenciesChecker {
if(_wei_count== 0) throw;
uint newTokens = (_wei_count * getMntTokensPerEth(icoTokensSold)) / (1 ether / 1 wei);
issueTokensInternal(_to,newTokens);
}
/// @dev This can be called to manually issue new tokens
/// from the bonus reward
function issueTokensExternal(address _to, uint _tokens) public onlyInState(State.ICOFinished) onlyTokenManager {
// can not issue more than BONUS_REWARD
if((issuedExternallyTokens + _tokens)>BONUS_REWARD){
throw;
}
mntToken.issueTokens(_to,_tokens);
issuedExternallyTokens = issuedExternallyTokens + _tokens;
}
function issueTokensInternal(address _to, uint _tokens) internal {
if((icoTokensSold + _tokens)>ICO_TOKEN_SUPPLY_LIMIT){
throw;
}
mntToken.issueTokens(_to,_tokens);
icoTokensSold+=_tokens;
LogBuy(_to,_tokens);
}
function burnTokens(address _from, uint _tokens) public onlyInState(State.ICOFinished) onlyTokenManager {
mntToken.burnTokens(_from,_tokens);
LogBurn(_from,_tokens);
}
// Default fallback function
function() payable {
// buyTokens -> issueTokensInternal
buyTokens(msg.sender);
}
} | only by Goldmint contract | function icoIsFinished() public {
if(msg.sender!=icoContractAddress){
throw;
}
icoIsFinishedDate = uint64(now);
}
| 10,618,686 |
pragma solidity >=0.4.24 <0.7.0;
//mport "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
import "./../libraries/States.sol";
contract FlightSuretyData {
using SafeMath for uint256;
using AirlineStates for AirlineStates.State;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct Airline {
string name;
string code;
uint256 votes;
uint256 funds;
address airlineAddress;
}
struct Vote {
address voter;
address airlineAddress;
}
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => bool) authorizedAppContracts;
mapping(address => Airline) private airlines;
mapping(bytes32 => bool) private votes;
mapping(bytes32 => Flight) private flights;
mapping(bytes32 => mapping(address => uint256)) private insurances;
address[] authorizedAirlinesArray = new address[](0);
AirlineStates.State private fundedAirlines;
AirlineStates.State private registeredAirlines;
AirlineStates.State private authorizedAirlines;
uint256 private airlineFundingAmount;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AuthorizedContractCaller(address appContract);
event DeAuthorizedContractCaller(address appContract);
event ChangedAirlineFundingAmount(uint256 amount);
event AirlineFunded(address airlineAddress);
event AirlineRegistered(address airlineAddress);
event AirlineAuthorized(address airlineAddress);
event AirlineVoted(address airlineAddress);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
authorizedAppContracts[contractOwner] = true;
airlineFundingAmount = 2 ether;
}
/********************************************************************************************/
/* 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 onlyFundedAirlines(address airlineAddress) {
require(fundedAirlines.has(airlineAddress), "Airline is not funded");
_;
}
modifier onlyRegisteredAirlines(address airlineAddress) {
require(
registeredAirlines.has(airlineAddress),
"Airline is not registered"
);
_;
}
modifier voteIsNotDuplicate(address voter, address candidate) {
Vote memory vote = Vote({voter: voter, airlineAddress: candidate});
bytes32 voteHash = keccak256(
abi.encodePacked(vote.voter, vote.airlineAddress)
);
require(!votes[voteHash], "This airline has already voted");
_;
}
modifier onlyAuthorizedAirlines(address airlineAddress) {
require(
authorizedAirlines.has(airlineAddress),
"Airline is not authorized"
);
_;
}
modifier onlyFlightOwner(address airline, string flight, uint256 timestamp) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require(
flights[flightKey].airline == airline,
"Only flight owner is allowed to do this"
);
_;
}
modifier paidEnough(uint256 amount) {
require(msg.value >= amount, "Have not paid enough");
_;
}
modifier checkValue(uint256 amount) {
_;
uint256 amountToRefund = msg.value.sub(amount);
msg.sender.transfer(amountToRefund);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**Function to authorize an application contract to call the data contract */
function authorizeCaller(address appContract)
external
requireContractOwner
{
authorizedAppContracts[appContract] = true;
emit AuthorizedContractCaller(appContract);
}
/**Function to authorize an application contract to call the data contract */
function deAuthorizeCaller(address appContract)
external
requireContractOwner
{
delete authorizedAppContracts[appContract];
emit DeAuthorizedContractCaller(appContract);
}
function changeAirlineFundingAmount(uint256 amount)
external
requireContractOwner
{
airlineFundingAmount = amount;
emit ChangedAirlineFundingAmount(amount);
}
function _fundAirline(address airlineAddress) internal {
fundedAirlines.addAirlineToState(airlineAddress);
emit AirlineFunded(airlineAddress);
}
function _registerAirline(address airlineAddress) internal {
registeredAirlines.addAirlineToState(airlineAddress);
emit AirlineRegistered(airlineAddress);
}
function _authorizeAirline(address airlineAddress) internal {
authorizedAirlines.addAirlineToState(airlineAddress);
authorizedAirlinesArray.push(airlineAddress);
emit AirlineAuthorized(airlineAddress);
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() external view returns (bool) {
return operational;
}
function getAirlineFundingAmount() external view returns (uint256) {
return airlineFundingAmount;
}
function registerFunds(
address passengerAddress,
address airlineAddress, string flight, uint256 timestamp,
uint256 amount
) external {
uint256 funds = airlines[airlineAddress].funds;
airlines[airlineAddress].funds = funds.add(amount);
bytes32 flightKey = getFlightKey(airlineAddress,flight,timestamp);
insurances[flightKey][passengerAddress] = amount;
}
function getPassengerInsuranceAmount(
address passengerAddress,
address airline,
string flight,
uint256 timestamp
) public view returns (uint256) {
if (!isPassengerInsured(passengerAddress, airline, flight, timestamp)) {
return 0;
} else {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return insurances[flightKey][passengerAddress];
}
}
/**
* @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 isAirlineRegistered(address airlineAddress)
public
view
returns (bool)
{
return registeredAirlines.has(airlineAddress);
}
function isAirlineFunded(address airlineAddress)
public
view
returns (bool)
{
return fundedAirlines.has(airlineAddress);
}
function fundAirline(address airlineAddress)
public
payable
requireIsOperational
paidEnough(airlineFundingAmount)
checkValue(airlineFundingAmount)
{
_fundAirline(airlineAddress);
if (isAirlineRegistered(airlineAddress)) {
uint256 airlineCount = getAuthorizedAirlineCount();
if (airlineCount < 4) {
authorizeAirline(airlineAddress);
} else {
uint256 totalVotes = getAirlineVoteCount(airlineAddress);
if (totalVotes >= airlineCount / 2) {
authorizeAirline(airlineAddress);
}
}
}
}
function getAirlineVoteCount(address airlineAddress)
public
view
onlyRegisteredAirlines(airlineAddress)
returns (uint256)
{
return airlines[airlineAddress].votes;
}
function getAuthorizedAirlineCount() internal view returns (uint256) {
return authorizedAirlinesArray.length;
}
function registerAirline(
address airlineToRegister,
string airlineCode,
string airlineName
) public requireIsOperational() {
require(
getAuthorizedAirlineCount() >= 4,
"Register directly only if there is at least 4 authorized airlines to vote"
);
Airline memory _airline = Airline({
name: airlineName,
code: airlineCode,
votes: 0,
funds: 0,
airlineAddress: airlineToRegister
});
airlines[_airline.airlineAddress] = _airline;
_registerAirline(airlineToRegister);
}
function registerAirline(
address airlineToRegister,
string airlineCode,
string airlineName,
address airlineRegistering
) public requireIsOperational() {
require(
getAuthorizedAirlineCount() < 4,
"Register another airline only if there is less than 4 authorized airlines"
);
require(
isAirlineAuthorized(airlineRegistering) ||
getAuthorizedAirlineCount() == 0,
"Only authorized airlines or first ever airline"
);
Airline memory _airline = Airline({
name: airlineName,
code: airlineCode,
votes: 0,
funds: 0,
airlineAddress: airlineToRegister
});
airlines[_airline.airlineAddress] = _airline;
_registerAirline(airlineToRegister);
}
function voteAirline(address votingAirline, address candidateAirline)
public
onlyAuthorizedAirlines(votingAirline)
onlyRegisteredAirlines(candidateAirline)
voteIsNotDuplicate(votingAirline, candidateAirline)
{
Vote memory vote = Vote({
voter: votingAirline,
airlineAddress: candidateAirline
});
airlines[candidateAirline].votes = airlines[candidateAirline].votes.add(
1
);
bytes32 voteHash = keccak256(
abi.encodePacked(vote.voter, vote.airlineAddress)
);
votes[voteHash] = true;
emit AirlineVoted(candidateAirline);
uint256 totalVotes = getAirlineVoteCount(candidateAirline);
uint256 airlineCount = getAuthorizedAirlineCount();
if (
totalVotes >= airlineCount / 2 && isAirlineFunded(candidateAirline)
) {
authorizeAirline(candidateAirline);
}
}
function getAirlineDetails(address airlineAddress)
public
view
onlyRegisteredAirlines(airlineAddress)
returns (
string name,
string code,
uint256 voteCount,
uint256 funds,
address airlAdd
)
{
Airline memory airline = airlines[airlineAddress];
name = airline.name;
code = airline.code;
voteCount = airline.votes;
funds = airline.funds;
airlAdd = airline.airlineAddress;
return (name, code, voteCount, funds, airlAdd);
}
function authorizeAirline(address airlineAddress)
public
requireIsOperational
onlyRegisteredAirlines(airlineAddress)
{
_authorizeAirline(airlineAddress);
}
function isAirlineAuthorized(address airlineAddress)
public
view
returns (bool)
{
return authorizedAirlines.has(airlineAddress);
}
function isPassengerInsured(address passengerAddress,address airline,
string flight,
uint256 timestamp)
public
view
returns (bool)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
uint256 amount = insurances[flightKey][passengerAddress];
if(amount == 0){
return false;
}else {
return true;
}
}
function registerFlight(address airline, string flight, uint256 timestamp)
external
requireIsOperational
onlyAuthorizedAirlines(airline)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].isRegistered = true;
flights[flightKey].updatedTimestamp = timestamp;
flights[flightKey].airline = airline;
}
function isFlightRegistered(
address airline,
string flight,
uint256 timestamp
) public view returns (bool) {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
if (flights[flightKey].isRegistered) {
return true;
} else {
return false;
}
}
function updateFlightStatus(
string flight,
uint256 timestamp,
uint8 statusCode,
address airline
) external requireIsOperational {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].statusCode = statusCode;
}
function fetchFlightStatus(string memory flight,
uint256 timestamp,
address airline) public view returns(uint256){
require(isFlightRegistered(airline, flight, timestamp), "The flight should exist before getting its status");
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return flights[flightKey].statusCode;
}
/**
* @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 {}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
// function() external payable {
// fund();
// }
}
| Credits payouts to insurees/ | function creditInsurees() external pure {}
| 13,032,535 |
./full_match/80001/0xaCD2BB9cA3849303dfdAB631eEE4D64dD83F5aC1/sources/contracts/PrimexProxyAdmin.sol | Changes the admin of the `beacon` to `newAdmin`. Requirements: - This contract must be the current admin of `proxy`./ | function changeBeaconProxyAdmin(
UpgradeableBeacon beacon,
address newAdmin
) external override onlyRole(BIG_TIMELOCK_ADMIN) {
beacon.transferOwnership(newAdmin);
}
| 5,673,044 |
./partial_match/5/0xC9a3DdadC753e6a7675Aa125991096623d06c437/sources/project_/contracts/governance/GoodDollarStaking.sol | Mint GOOD rewards of the staker user Receipent address of the rewards return amount of the minted rewards emits 'ReputationEarned' event for staker earned GOOD amount/try to mint only if have minter permission, so user can always withdraw his funds without this reverting | function _mintGOODRewards(address user) internal returns (uint256 amount) {
if (
nameService.getAddress("GDAO_STAKING") == address(this) ||
AccessControl(nameService.getAddress("REPUTATION")).hasRole(
keccak256("MINTER_ROLE"),
address(this)
)
) {
amount = _issueEarnedRewards(address(this), user, 0, block.number);
if (amount > 0) {
ERC20(nameService.getAddress("REPUTATION")).mint(user, amount);
emit ReputationEarned(msg.sender, amount);
}
}
return amount;
}
| 16,856,427 |
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20 as OZIERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath as OZSafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol";
import "./OracleSimple.sol";
contract Dripper is Ownable {
using OZSafeMath for uint256;
struct DripParams {
uint transitionTime;
uint dripInterval;
uint maxTWAPDifferencePct;
uint maxSlippageTolerancePct;
}
enum DripStatus {
SET,
RUNNING,
DONE
}
DripStatus public dripStatus;
/**
* startTime: the starting timestamp of the drip process
* transitionTime: the total time the drip process will run for
* dripInterval: the minimum time between drip calls which will be enforced by the contract
* maxTWAPDifferencePct: the maximum twap difference tolerance, expressed as a percentage where 1e18 represents 100%
* maxSlippageTolerancePct the maximum slippage tolerance, expressed as a percentage where 1e18 represents 100%
* amountToDrip: the total amount of starting LP tokens that the drip function will consume
*/
struct DripConfig {
uint startTime;
uint transitionTime;
uint dripInterval;
uint maxTWAPDifferencePct;
uint maxSlippageTolerancePct;
uint amountToDrip;
uint amountDripped;
}
DripConfig public dripConfig;
uint256 public latestDripTime;
string public constant ERROR_FAR_FROM_TWAP = "Dripper: Converter LP price is too far from TWAP.";
string public constant ERROR_DRIP_INTERVAL = "Dripper: Drip interval has not passed.";
string public constant ERROR_ALREADY_CONFIGURED = "Dripper: Already configured.";
string public constant ERROR_INTOLERABLE_SLIPPAGE = "Dripper: Slippage exceeds configured limit.";
string public constant ERROR_DRIP_NOT_RUNNING = "Dripper: Drip process is not currently runnning.";
string public constant ERROR_DRIP_NOT_DONE = "Dripper: Drip process has not ended.";
uint256 private constant ONE = 10**18;
IUniswapV2Pair public startLP; // WETH-AGVE
IUniswapV2Pair public endLP; // HNY-AGVE
IUniswapV2Pair public conversionLP; // HNY-WETH
IUniswapV2Router02 public router;
OZIERC20 public startToken; // WETH
OZIERC20 public endToken; // HNY
OZIERC20 public baseToken; // AGVE
OracleSimple public twapOracle;
address public holder;
event Drip(uint256 price, uint256 baseTokenAdded, uint256 endTokenAdded);
event DripEnded();
event TokenRetrieved(address token, uint256 balance);
/**
* @notice Configure essential drip parameters, and start the timer.
* @dev Sets up the drip parameters, and starts the drip counter.
* This function is in charge of setting up who the holder of
* the tokens is. In case the LP token holder is whoever deployed
* the contract, you should set the deployer's address as the holder.
* @param _baseToken the token that is shared between thet starting LP and the end LP
* @param _startToken the starting LP specific token
* @param _endToken the ending LP specific token
* @param _router the address of the Uniswap Router that knows the pools we're going to interact with
* @param _twapOracle the TWAP oracle that keeps track of LP states
* @param _dripConfig the configuration parameters for the drippping process
*/
constructor(
address _startToken,
address _endToken,
address _baseToken,
address payable _router,
address _twapOracle,
DripParams memory _dripConfig
) public Ownable() {
router = IUniswapV2Router02(_router);
IUniswapV2Factory factory = IUniswapV2Factory(router.factory());
startToken = OZIERC20(_startToken);
endToken = OZIERC20(_endToken);
baseToken = OZIERC20(_baseToken);
startLP = IUniswapV2Pair(factory.getPair(_startToken, _baseToken));
endLP = IUniswapV2Pair(factory.getPair(_endToken, _baseToken));
conversionLP = IUniswapV2Pair(factory.getPair(_startToken, _endToken));
twapOracle = OracleSimple(_twapOracle);
dripConfig = DripConfig(
block.timestamp,
_dripConfig.transitionTime,
_dripConfig.dripInterval,
_dripConfig.maxTWAPDifferencePct,
_dripConfig.maxSlippageTolerancePct,
0, // will be set up when startDripping is called
0
);
dripStatus = DripStatus.SET;
}
/**
* @notice start the dripping process. This function is separate since it might take
* a long while to set any token approval after contract deplyment.
* @param _tokenHolder the address that holds the LP tokens we will interact with
* @param _amountToDrip the amount of start LP tokens whose value we will drip
*/
function startDripping(address _tokenHolder, uint256 _amountToDrip) public onlyOwner {
require(dripStatus == DripStatus.SET, "Cannot start twice.");
holder = _tokenHolder;
dripConfig.amountToDrip = _amountToDrip;
dripConfig.startTime = block.timestamp;
dripStatus = DripStatus.RUNNING;
}
/**
* @notice Execute a drip.
* @dev This function does the dripping of value from a LP into another LP
* It should check that the price has not deviated too much from TWAP
* and that the swap slippage in the conversion LP is acceptable.
* Note that it is public since it doesn't use msg.sender - and it also
* is time-capped so that it can't be successfully called before the
* dripInterval passes.
*/
function drip() public {
require(dripStatus == DripStatus.RUNNING, ERROR_DRIP_NOT_RUNNING);
require(now >= latestDripTime.add(dripConfig.dripInterval), ERROR_DRIP_INTERVAL);
// check current fromToken -> endToken price doesn't deviate too much from TWAP
uint256 price = _checkPrice();
uint256 lpTokensToWithdraw = _calculateDrip();
// Ingest tokens on drip() call
require(
startLP.transferFrom(holder, address(this), lpTokensToWithdraw)
);
(uint256 startTokenAmt, uint256 baseTokenAmt) = _withdraw(lpTokensToWithdraw);
dripConfig.amountDripped = dripConfig.amountDripped.add(lpTokensToWithdraw);
uint256 endTokenAmt = _swapTokens(startTokenAmt);
(endTokenAmt, baseTokenAmt) = _optimizeAmounts(
endTokenAmt, baseTokenAmt
);
_addLiquidity(endTokenAmt, baseTokenAmt);
latestDripTime = now;
emit Drip(price, baseTokenAmt, endTokenAmt);
if (dripConfig.amountDripped >= dripConfig.amountToDrip) {
_endDrip();
}
}
/**
* @notice Retrieve this contract's balance of tokenToRetrieve
* @dev Helper method to retrieve stuck tokens. Should only be called once the drip is over.
* @param tokenToRetrieve The address for the token whose balance you want to retrieve.
*/
function retrieve(address tokenToRetrieve) public onlyOwner {
require(dripStatus == DripStatus.DONE, ERROR_DRIP_NOT_DONE);
OZIERC20 token = OZIERC20(tokenToRetrieve);
uint256 myBalance = token.balanceOf(address(this));
if (myBalance > 0) {
require(token.transfer(
holder==address(0)?
owner() : holder,
myBalance
)
);
emit TokenRetrieved(address(token), myBalance);
}
}
/**
* @notice End the drip process and retrieve all known tokens.
*/
function abort() public onlyOwner {
_endDrip();
retrieve(address(startLP));
retrieve(address(endLP));
retrieve(address(startToken));
retrieve(address(endToken));
retrieve(address(baseToken));
}
/**
* @dev Helper method to consult the current TWAP.
*/
function _getConversionTWAP() internal view returns (uint256 twap) {
return twapOracle.consult(address(startToken), ONE);
}
/**
* @dev Helper method to get the price between startToken and endToken.
*/
function _getConversionPrice() internal view returns (uint256 quote) {
return _getQuote(address(startToken), address(endToken));
}
/**
* @notice Gets a quote for the price of tokenB in terms of tokenA.
* i.e. if 1 TKA = 3 TKB then getQuote(TKA, TKB) = 0.3333...
* Results expressed with 1e18 being 1.
*/
function _getQuote(address tokenA, address tokenB) internal view returns (uint256 quote) {
IUniswapV2Pair pair = IUniswapV2Pair(
IUniswapV2Factory(router.factory()).getPair(tokenA, tokenB)
);
(uint112 balance0, uint112 balance1, ) = pair.getReserves();
if (address(tokenA) == pair.token0()) {
return UniswapV2Library.quote(ONE, balance0, balance1);
} else {
return UniswapV2Library.quote(ONE, balance1, balance0);
}
}
function _endDrip() internal {
dripStatus = DripStatus.DONE;
emit DripEnded();
}
/**
* @notice Checks that the current pool price is not too far from TWAP
*/
function _checkPrice() internal view returns (uint256 curPrice) {
uint256 price = _getConversionPrice();
uint256 twap = _getConversionTWAP();
require(
twap.mul(ONE).div(price) < ONE.add(dripConfig.maxTWAPDifferencePct)
&& price.mul(ONE).div(twap) < ONE.add(dripConfig.maxTWAPDifferencePct),
ERROR_FAR_FROM_TWAP
);
return price;
}
/**
* @notice Calculates how much startLP tokens we have to drip right now
* Clamps the returned value to the remaining drip amount.
*/
function _calculateDrip() internal view returns (uint256 dripAmt) {
// calculate how much should be withdrawn
uint256 timeSinceLastDrip = block.timestamp.sub(
latestDripTime < dripConfig.startTime ?
dripConfig.startTime : latestDripTime
);
uint256 startLPToWithdraw = dripConfig.amountToDrip.mul(
timeSinceLastDrip.mul(ONE).div(dripConfig.transitionTime)
).div(ONE);
uint256 remainingDrip = dripConfig.amountToDrip.sub(dripConfig.amountDripped);
if (remainingDrip < startLPToWithdraw) {
return remainingDrip;
}
return startLPToWithdraw;
}
/**
* @notice Swaps `amountIn` start tokens for end tokens
* @param amountIn the amount of startTokens to swap
* @return amountOut the output of the swap in endTokens
*/
function _swapTokens(uint256 amountIn) internal returns (uint256 amountOut) {
// swap fromToken to endToken
address[] memory path = new address[](2);
path[0] = address(startToken);
path[1] = address(endToken);
// Calculate minimum expected output, taking slippage into account
uint256 expectedOutput = _getQuote(address(startToken), address(endToken)).mul(amountIn).div(ONE);
expectedOutput = expectedOutput.mul(ONE.sub(dripConfig.maxSlippageTolerancePct)).div(ONE);
startToken.approve(address(router), amountIn);
uint[] memory amounts = router.swapExactTokensForTokens(
amountIn,
1,
path,
address(this),
now + 1
);
return amounts[amounts.length.sub(1)];
}
/**
* @notice Optimize token amounts for addition into a liquidity pool
* @param endAmount initial guess on how much endTokens to add
* @param baseAmount initial guess on how much baseTokens to add
* @return optimized endTokenAmount and baseTokenAmount
*/
function _optimizeAmounts(uint256 endAmount, uint256 baseAmount) internal view returns (uint256, uint256) {
// optimize token amounts to add as liquidity
// based on the amount tokens we've got
uint256 quote = _getQuote(address(endToken), address(baseToken));
uint256 optimizedBaseTokenAmount = quote.mul(endAmount).div(ONE);
uint256 optimizedEndTokenAmount = ONE.div(quote).mul(baseAmount);
// optimize one side, if not, optimize the other.
if (optimizedBaseTokenAmount <= baseAmount){
return (endAmount, optimizedBaseTokenAmount);
} else {
return (optimizedEndTokenAmount, baseAmount);
}
}
/**
* @notice Adds liquidity to the endToken/baseToken liquidity pool
* @param endAmount the amount of endTokens to add
* @param baseAmount the amount of baseTokens to add
*/
function _addLiquidity(uint256 endAmount, uint256 baseAmount) internal {
// add fromToken and necessary amount of baseToken to endLP
endToken.approve(address(router), endAmount);
baseToken.approve(address(router), baseAmount);
// actually add the liquidity
router.addLiquidity(
address(endToken),
address(baseToken),
endAmount,
baseAmount,
1,
baseAmount,
holder,
now + 1
);
}
/**
* @notice Withdraws some startLP tokens for their locked collateral
* @param startLPAmount the amount of LP tokens to burn
* @return (startAmt, baseAmt) the amount of startToken and baseToken retrieved from the LP token burn
*/
function _withdraw(uint256 startLPAmount) internal returns (uint256, uint256) {
startLP.approve(address(router), startLPAmount);
// withdraw it
return router.removeLiquidity(
address(startToken),
address(baseToken),
startLPAmount,
1, 1,
address(this),
now + 1
);
}
}
| Helper method to get the price between startToken and endToken./ | function _getConversionPrice() internal view returns (uint256 quote) {
return _getQuote(address(startToken), address(endToken));
}
| 5,530,085 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ARTHGmuRebaseERC20 } from "./ARTHGmuRebaseERC20.sol";
contract ArthUSDWrapper is ARTHGmuRebaseERC20 {
IERC20 public arth;
event Deposit(address indexed who, uint256 amount);
event Withdraw(address indexed who, uint256 amount);
constructor(
string memory _name,
string memory _symbol,
address _arth,
address _gmuOracle,
address governance,
uint256 chainId
) ARTHGmuRebaseERC20(_name, _symbol, _gmuOracle, governance, chainId) {
arth = IERC20(_arth);
_transferOwnership(governance); // transfer ownership to governance
}
/**
* @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
*/
function depositFor(address account, uint256 amount) public virtual returns (bool) {
SafeERC20.safeTransferFrom(arth, _msgSender(), address(this), amount);
_mint(account, amount);
emit Deposit(account, amount);
return true;
}
function deposit(uint256 amount) public virtual returns (bool) {
return depositFor(_msgSender(), amount);
}
/**
* @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
*/
function withdrawTo(address account, uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
SafeERC20.safeTransfer(arth, account, amount);
emit Withdraw(account, amount);
return true;
}
function withdraw(uint256 amount) public virtual returns (bool) {
return withdrawTo(_msgSender(), amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IGMUOracle } from "./interfaces/IGMUOracle.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { ERC20RebasePermit } from "./ERC20RebasePermit.sol";
contract ARTHGmuRebaseERC20 is ERC20RebasePermit, Ownable {
using SafeMath for uint256;
IGMUOracle public gmuOracle;
uint8 public decimals = 18;
string public symbol;
event GmuOracleChange(address indexed oracle);
constructor(
string memory _name,
string memory _symbol,
address _gmuOracle,
address governance,
uint256 chainId
) ERC20RebasePermit(_name, chainId) {
symbol = _symbol;
setGMUOracle(_gmuOracle);
_transferOwnership(governance); // transfer ownership to governance
}
function gonsPerFragment()
public
view
override
returns (uint256)
{
// make the gons per fragment be as per the gmu oracle
return gmuOracle.getPrice();
}
function gonsDecimals()
public
view
override
virtual
returns (uint256)
{
return gmuOracle.getDecimalPercision();
}
/**
* @dev only governance can change the gmu oracle
*/
function setGMUOracle(address _gmuOracle)
public
onlyOwner
{
gmuOracle = IGMUOracle(_gmuOracle);
emit GmuOracleChange(_gmuOracle);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// 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 (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 (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: Unlicense
pragma solidity ^0.8.0;
interface IGMUOracle {
function getPrice() external view returns (uint256);
function getDecimalPercision() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
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 generally not needed starting with Solidity 0.8, since 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: Unlicense
pragma solidity ^0.8.0;
import {ERC20Rebase} from "./ERC20Rebase.sol";
import {ITransferReceiver} from "./interfaces/ITransferReceiver.sol";
contract ERC20RebasePermit is ERC20Rebase {
string public name;
mapping(address => uint256) public nonces;
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
bytes32 public constant TRANSFER_TYPEHASH =
keccak256(
"Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)"
);
constructor(string memory _name, uint256 chainId) {
name = _name;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) public virtual returns (bool) {
require(
to != address(0) || to != address(this),
"ARTH.usd: bad `to` address"
);
uint256 balance = balanceOf(msg.sender);
require(balance >= value, "ARTH.usd: transfer exceeds balance");
_transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
function transferWithPermit(
address target,
address to,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (bool) {
require(block.timestamp <= deadline, "ARTH.usd: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline
)
);
require(
_verifyEIP712(target, hashStruct, v, r, s) ||
_verifyPersonalSign(target, hashStruct, v, r, s),
"ARTH.usd: bad signature"
);
// NOTE: is this check needed, was there in the refered contract.
require(
to != address(0) || to != address(this),
"ARTH.usd: bad `to` address"
);
require(
balanceOf(target) >= value,
"ARTH.usd: transfer exceeds balance"
);
_transfer(target, to, value);
return true;
}
function _verifyEIP712(
address target,
bytes32 hashStruct,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)
);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
/// @dev Builds a _prefixed hash to mimic the behavior of eth_sign.
function _prefixed(bytes32 hash) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
function _verifyPersonalSign(
address target,
bytes32 hashStruct,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (bool) {
bytes32 hash = _prefixed(hashStruct);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract ERC20Rebase is IERC20 {
using SafeMath for uint256;
uint256 internal _totalSupply;
uint256 internal _gonsPerFragment = 1e6;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
function gonsPerFragment() public view virtual returns (uint256) {
return _gonsPerFragment;
}
function gonsDecimals() public view virtual returns (uint256) {
return 6;
}
function gonsPercision() public view virtual returns (uint256) {
return 10**gonsDecimals();
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply.mul(gonsPerFragment()).div(gonsPercision());
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account].mul(gonsPerFragment()).div(gonsPercision());
}
function underlyingBalanceOf(address account)
public
view
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(msg.sender, 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(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`s tokens of at least
* `amount`.
*
* NOTE: The `spender i.e msg.sender` and the `owner` both should not be blacklisted.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(
amount,
"ARTH.usd: 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(
msg.sender,
spender,
_allowances[msg.sender][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(
subtractedValue,
"ARTH.usd: 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`.
*
* NOTE: The `sender` should not be blacklisted.
*/
function _transfer(
address sender,
address recipient,
uint256 value
) internal {
// get amount in underlying
uint256 gonValues = value.div(gonsPerFragment()).mul(gonsPercision());
// sub from balance of sender
_balances[sender] = _balances[sender].sub(gonValues);
// add to balance of receiver
_balances[recipient] = _balances[recipient].add(gonValues);
emit Transfer(sender, recipient, value);
}
function _mint(address account, uint256 gonValues) internal {
require(account != address(0), "ARTH.usd: mint to the zero address");
uint256 amount = gonValues.mul(gonsPerFragment()).div(gonsPercision());
_totalSupply = _totalSupply.add(gonValues);
_balances[account] = _balances[account].add(gonValues);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 gonValues) internal {
require(account != address(0), "ARTH.usd: burn from the zero address");
uint256 amount = gonValues.mul(gonsPerFragment()).div(gonsPercision());
_balances[account] = _balances[account].sub(
gonValues,
"ARTH.usd: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(gonValues);
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), "ARTH: approve from zero");
require(spender != address(0), "ARTH: approve to zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface ITransferReceiver {
function onTokenTransfer(
address,
uint256,
bytes calldata
) external returns (bool);
} | Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens./ | function depositFor(address account, uint256 amount) public virtual returns (bool) {
SafeERC20.safeTransferFrom(arth, _msgSender(), address(this), amount);
_mint(account, amount);
emit Deposit(account, amount);
return true;
}
| 13,999,110 |
pragma solidity ^0.5.16;
// Inheritance
import "./Owned.sol";
import "./interfaces/ISupplySchedule.sol";
// Libraries
import "./SafeDecimalMath.sol";
import "./Math.sol";
// Internal references
import "./Proxy.sol";
import "./interfaces/ISynthetix.sol";
import "./interfaces/IERC20.sol";
contract SupplySchedule is Owned, ISupplySchedule {
using SafeMath for uint;
using SafeDecimalMath for uint;
using Math for uint;
// Time of the last inflation supply mint event
uint public lastMintEvent;
// Counter for number of days since the start of supply inflation
uint public dayCounter;
uint public constant DAYS_PER_YEAR = 365;
// The number of SDIP rewarded to the caller of Synthetix.mint()
uint public minterReward = 20 * SafeDecimalMath.unit();
// The initial daily inflationary supply
uint public constant INITIAL_DAILY_SUPPLY = 864000 * 1e18;
// Address of the SynthetixProxy for the onlySynthetix modifier
address payable public synthetixProxy;
// Max SDIP rewards for minter
uint public constant MAX_MINTER_REWARD = 200 * 1e18;
// How long each inflation period is before mint can be called
uint public constant MINT_PERIOD_DURATION = 1 days;
uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00
// Yearly percentage decay of inflationary supply
uint public constant DECAY_RATE = 500000000000000000; // 50% yearly
constructor(
address _owner,
uint _lastMintEvent
) public Owned(_owner) {
lastMintEvent = _lastMintEvent;
dayCounter = 0;
}
// ========== VIEWS ==========
/**
* @return The amount of SNX mintable for the inflationary supply
*/
function mintableSupply() external view returns (uint) {
uint totalAmount;
if (!isMintable()) {
return totalAmount;
}
uint currentDay = dayCounter;
uint remainingDaysToMint = daysSinceLastIssuance();
// Calculate total mintable supply from exponential decay function
while (remainingDaysToMint > 0) {
currentDay++;
uint daySupply = getDaySupply(currentDay);
totalAmount = totalAmount.add(daySupply);
remainingDaysToMint--;
}
return totalAmount;
}
function getDaySupply(uint _dayCounter) internal view returns (uint) {
uint numOfYears = _dayCounter.div(DAYS_PER_YEAR);
uint effectiveDecay = (DECAY_RATE).powDecimal(numOfYears);
uint supplyForDay = INITIAL_DAILY_SUPPLY.multiplyDecimal(effectiveDecay);
return supplyForDay;
}
/**
* @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor)
* @return Calculate the numberOfDays since last mint rounded down to 1 day
*/
function daysSinceLastIssuance() public view returns (uint) {
// Get days since lastMintEvent
// If lastMintEvent not set or 0, then start from inflation start date.
uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);
return timeDiff.div(MINT_PERIOD_DURATION);
}
/**
* @return boolean whether the MINT_PERIOD_DURATION (1 days)
* has passed since the lastMintEvent.
* */
function isMintable() public view returns (bool) {
if (now - lastMintEvent > MINT_PERIOD_DURATION) {
return true;
}
return false;
}
// ========== MUTATIVE FUNCTIONS ==========
/**
* @notice Record the mint event from Synthetix by incrementing the inflation
* week counter for the number of weeks minted (probabaly always 1)
* and store the time of the event.
* @param supplyMinted the amount of SNX the total supply was inflated by.
* */
function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) {
uint numberOfDaysIssued = daysSinceLastIssuance();
// add number of weeks minted to dayCounter
dayCounter = dayCounter.add(numberOfDaysIssued);
// Update mint event to latest day issued (start date + number of days issued * seconds in day)
lastMintEvent = INFLATION_START_DATE.add(dayCounter.mul(MINT_PERIOD_DURATION));
emit SupplyMinted(supplyMinted, numberOfDaysIssued, lastMintEvent, now);
return true;
}
/**
* @notice Sets the reward amount of SNX for the caller of the public
* function Synthetix.mint().
* This incentivises anyone to mint the inflationary supply and the mintr
* Reward will be deducted from the inflationary supply and sent to the caller.
* @param amount the amount of SNX to reward the minter.
* */
function setMinterReward(uint amount) external onlyOwner {
require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward");
minterReward = amount;
emit MinterRewardUpdated(minterReward);
}
// ========== SETTERS ========== */
/**
* @notice Set the SynthetixProxy should it ever change.
* SupplySchedule requires Synthetix address as it has the authority
* to record mint event.
* */
function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner {
require(address(_synthetixProxy) != address(0), "Address cannot be 0");
synthetixProxy = address(uint160(address(_synthetixProxy)));
emit SynthetixProxyUpdated(synthetixProxy);
}
// ========== MODIFIERS ==========
/**
* @notice Only the Synthetix contract is authorised to call this function
* */
modifier onlySynthetix() {
require(
msg.sender == address(Proxy(address(synthetixProxy)).target()),
"Only the synthetix contract can perform this action"
);
_;
}
/* ========== EVENTS ========== */
/**
* @notice Emitted when the inflationary supply is minted
* */
event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp);
/**
* @notice Emitted when the SNX minter reward amount is updated
* */
event MinterRewardUpdated(uint newRewardAmount);
/**
* @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address
* */
event SynthetixProxyUpdated(address newAddress);
}
| Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) return Calculate the numberOfDays since last mint rounded down to 1 day/ Get days since lastMintEvent If lastMintEvent not set or 0, then start from inflation start date. | function daysSinceLastIssuance() public view returns (uint) {
uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);
return timeDiff.div(MINT_PERIOD_DURATION);
}
| 5,350,488 |
./full_match/1/0x1091588Cc431275F99DC5Df311fd8E1Ab81c89F3/sources/contracts/vault/VaultCore.sol | Convert a quantity of a token into 1e18 fixed decimal "units" in the underlying base (USD/ETH) used by the vault. Price is not taken into account, only quantity. Examples of this conversion: - 1e18 DAI becomes 1e18 units (same decimals) - 1e6 USDC becomes 1e18 units (decimal conversion) - 1e18 rETH becomes 1.2e18 units (exchange rate conversion) _raw Quantity of asset _asset Core Asset address return value 1e18 normalized quantity of units/ | function _toUnits(uint256 _raw, address _asset)
internal
view
returns (uint256)
{
UnitConversion conversion = assets[_asset].unitConversion;
if (conversion == UnitConversion.DECIMALS) {
return _raw.scaleBy(18, _getDecimals(_asset));
uint256 exchangeRate = IGetExchangeRateToken(_asset)
.getExchangeRate();
return (_raw * exchangeRate) / 1e18;
require(false, "Unsupported conversion type");
}
}
| 2,958,604 |
pragma solidity ^0.4.24;
/**
https://fortisgames.com https://fortisgames.com https://fortisgames.com https://fortisgames.com https://fortisgames.com
FFFFFFFFFFFFFFFFFFFFFF tttt iiii
F::::::::::::::::::::F ttt:::t i::::i
F::::::::::::::::::::F t:::::t iiii
FF::::::FFFFFFFFF::::F t:::::t
F:::::F FFFFFFooooooooooo rrrrr rrrrrrrrr ttttttt:::::ttttttt iiiiiii ssssssssss
F:::::F oo:::::::::::oo r::::rrr:::::::::r t:::::::::::::::::t i:::::i ss::::::::::s
F::::::FFFFFFFFFFo:::::::::::::::or:::::::::::::::::r t:::::::::::::::::t i::::i ss:::::::::::::s
F:::::::::::::::Fo:::::ooooo:::::orr::::::rrrrr::::::rtttttt:::::::tttttt i::::i s::::::ssss:::::s
F:::::::::::::::Fo::::o o::::o r:::::r r:::::r t:::::t i::::i s:::::s ssssss
F::::::FFFFFFFFFFo::::o o::::o r:::::r rrrrrrr t:::::t i::::i s::::::s
F:::::F o::::o o::::o r:::::r t:::::t i::::i s::::::s
F:::::F o::::o o::::o r:::::r t:::::t tttttt i::::i ssssss s:::::s
FF:::::::FF o:::::ooooo:::::o r:::::r t::::::tttt:::::ti::::::is:::::ssss::::::s
F::::::::FF o:::::::::::::::o r:::::r tt::::::::::::::ti::::::is::::::::::::::s
F::::::::FF oo:::::::::::oo r:::::r tt:::::::::::tti::::::i s:::::::::::ss
FFFFFFFFFFF ooooooooooo rrrrrrr ttttttttttt iiiiiiii sssssssssss
Discord: https://discord.gg/gDtTX62
An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles.
Bankroll contract, containing tokens purchased from all dividend-card profit and ICO dividends.
Acts as token repository for games on the Zethr platform.
**/
contract ZTHInterface {
function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass) public payable returns (uint);
function balanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool);
function exit() public;
function sell(uint amountOfTokens) public;
function withdraw(address _recipient) public;
}
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
contract ZethrBankroll is ERC223Receiving {
using SafeMath for uint;
/*=================================
= EVENTS =
=================================*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WhiteListAddition(address indexed contractAddress);
event WhiteListRemoval(address indexed contractAddress);
event RequirementChange(uint required);
event DevWithdraw(uint amountTotal, uint amountPerPerson);
event EtherLogged(uint amountReceived, address sender);
event BankrollInvest(uint amountReceived);
event DailyTokenAdmin(address gameContract);
event DailyTokensSent(address gameContract, uint tokens);
event DailyTokensReceived(address gameContract, uint tokens);
/*=================================
= WITHDRAWAL CONSTANTS =
=================================*/
uint constant public MAX_OWNER_COUNT = 10;
uint constant public MAX_WITHDRAW_PCT_DAILY = 15;
uint constant public MAX_WITHDRAW_PCT_TX = 5;
uint constant internal resetTimer = 1 days;
/*=================================
= ZTH INTERFACE =
=================================*/
address internal zethrAddress;
ZTHInterface public ZTHTKN;
/*=================================
= VARIABLES =
=================================*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
mapping (address => bool) public isWhitelisted;
mapping (address => uint) public dailyTokensPerContract;
address internal divCardAddress;
address[] public owners;
address[] public whiteListedContracts;
uint public required;
uint public transactionCount;
uint internal dailyResetTime;
uint internal dailyTknLimit;
uint internal tknsDispensedToday;
bool internal reEntered = false;
/*=================================
= CUSTOM CONSTRUCTS =
=================================*/
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
struct TKN {
address sender;
uint value;
}
/*=================================
= MODIFIERS =
=================================*/
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier contractIsNotWhiteListed(address contractAddress) {
if (isWhitelisted[contractAddress])
revert();
_;
}
modifier contractIsWhiteListed(address contractAddress) {
if (!isWhitelisted[contractAddress])
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (!isOwner[caller])
revert();
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
/*=================================
= LIST OF OWNERS =
=================================*/
/*
This list is for reference/identification purposes only, and comprises the eight core Zethr developers.
For game contracts to be listed, they must be approved by a majority (i.e. currently five) of the owners.
Contracts can be delisted in an emergency by a single owner.
0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae // Norsefire
0x11e52c75998fe2E7928B191bfc5B25937Ca16741 // klob
0x20C945800de43394F70D789874a4daC9cFA57451 // Etherguy
0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB // blurr
0x8537aa2911b193e5B377938A723D805bb0865670 // oguzhanox
0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3 // Randall
0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696 // cryptodude
0xDa83156106c4dba7A26E9bF2Ca91E273350aa551 // TropicalRogue
*/
/*=================================
= PUBLIC FUNCTIONS =
=================================*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor (address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
dailyResetTime = now - (1 days);
}
/** Testing only.
function exitAll()
public
{
uint tokenBalance = ZTHTKN.balanceOf(address(this));
ZTHTKN.sell(tokenBalance - 1e18);
ZTHTKN.sell(1e18);
ZTHTKN.withdraw(address(0x0));
}
**/
function addZethrAddresses(address _zethr, address _divcards)
public
isAnOwner
{
zethrAddress = _zethr;
divCardAddress = _divcards;
ZTHTKN = ZTHInterface(zethrAddress);
}
/// @dev Fallback function allows Ether to be deposited.
function()
public
payable
{
}
uint NonICOBuyins;
function deposit()
public
payable
{
NonICOBuyins = NonICOBuyins.add(msg.value);
}
/// @dev Function to buy tokens with contract eth balance.
function buyTokens()
public
payable
isAnOwner
{
uint savings = address(this).balance;
if (savings > 0.01 ether) {
ZTHTKN.buyAndSetDivPercentage.value(savings)(address(0x0), 33, "");
emit BankrollInvest(savings);
}
else {
emit EtherLogged(msg.value, msg.sender);
}
}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/) public returns (bool) {
// Nothing, for now. Just receives tokens.
}
/// @dev Calculates if an amount of tokens exceeds the aggregate daily limit of 15% of contract
/// balance or 5% of the contract balance on its own.
function permissibleTokenWithdrawal(uint _toWithdraw)
public
returns(bool)
{
uint currentTime = now;
uint tokenBalance = ZTHTKN.balanceOf(address(this));
uint maxPerTx = (tokenBalance.mul(MAX_WITHDRAW_PCT_TX)).div(100);
require (_toWithdraw <= maxPerTx);
if (currentTime - dailyResetTime >= resetTimer)
{
dailyResetTime = currentTime;
dailyTknLimit = (tokenBalance.mul(MAX_WITHDRAW_PCT_DAILY)).div(100);
tknsDispensedToday = _toWithdraw;
return true;
}
else
{
if (tknsDispensedToday.add(_toWithdraw) <= dailyTknLimit)
{
tknsDispensedToday += _toWithdraw;
return true;
}
else { return false; }
}
}
/// @dev Allows us to set the daily Token Limit
function setDailyTokenLimit(uint limit)
public
isAnOwner
{
dailyTknLimit = limit;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
validRequirement(owners.length, required)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txToExecute = transactions[transactionId];
txToExecute.executed = true;
if (txToExecute.destination.call.value(txToExecute.value)(txToExecute.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txToExecute.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*=================================
= OPERATOR FUNCTIONS =
=================================*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
// Additions for Bankroll
function whiteListContract(address contractAddress)
public
isAnOwner
contractIsNotWhiteListed(contractAddress)
notNull(contractAddress)
{
isWhitelisted[contractAddress] = true;
whiteListedContracts.push(contractAddress);
// We set the daily tokens for a particular contract in a separate call.
dailyTokensPerContract[contractAddress] = 0;
emit WhiteListAddition(contractAddress);
}
// Remove a whitelisted contract. This is an exception to the norm in that
// it can be invoked directly by any owner, in the event that a game is found
// to be bugged or otherwise faulty, so it can be shut down as an emergency measure.
// Iterates through the whitelisted contracts to find contractAddress,
// then swaps it with the last address in the list - then decrements length
function deWhiteListContract(address contractAddress)
public
isAnOwner
contractIsWhiteListed(contractAddress)
{
isWhitelisted[contractAddress] = false;
for (uint i=0; i < whiteListedContracts.length - 1; i++)
if (whiteListedContracts[i] == contractAddress) {
whiteListedContracts[i] = owners[whiteListedContracts.length - 1];
break;
}
whiteListedContracts.length -= 1;
emit WhiteListRemoval(contractAddress);
}
function contractTokenWithdraw(uint amount, address target) public
contractIsWhiteListed(msg.sender)
{
require(isWhitelisted[msg.sender]);
require(ZTHTKN.transfer(target, amount));
}
// Alters the amount of tokens allocated to a game contract on a daily basis.
function alterTokenGrant(address _contract, uint _newAmount)
public
isAnOwner
contractIsWhiteListed(_contract)
{
dailyTokensPerContract[_contract] = _newAmount;
}
function queryTokenGrant(address _contract)
public
view
returns (uint)
{
return dailyTokensPerContract[_contract];
}
// Function to be run by an owner (ideally on a cron job) which performs daily
// token collection and dispersal for all whitelisted contracts.
function dailyAccounting()
public
isAnOwner
{
for (uint i=0; i < whiteListedContracts.length; i++)
{
address _contract = whiteListedContracts[i];
if ( dailyTokensPerContract[_contract] > 0 )
{
allocateTokens(_contract);
emit DailyTokenAdmin(_contract);
}
}
}
// In the event that we want to manually take tokens back from a whitelisted contract,
// we can do so.
function retrieveTokens(address _contract, uint _amount)
public
isAnOwner
contractIsWhiteListed(_contract)
{
require(ZTHTKN.transferFrom(_contract, address(this), _amount));
}
// Dispenses daily amount of ZTH to whitelisted contract, or retrieves the excess.
// Block withdraws greater than MAX_WITHDRAW_PCT_TX of Zethr token balance.
// (May require occasional adjusting of the daily token allocation for contracts.)
function allocateTokens(address _contract)
public
isAnOwner
contractIsWhiteListed(_contract)
{
uint dailyAmount = dailyTokensPerContract[_contract];
uint zthPresent = ZTHTKN.balanceOf(_contract);
// Make sure that tokens aren't sent to a contract which is in the black.
if (zthPresent <= dailyAmount)
{
// We need to send tokens over, make sure it's a permitted amount, and then send.
uint toDispense = dailyAmount.sub(zthPresent);
// Make sure amount is <= tokenbalance*MAX_WITHDRAW_PCT_TX
require(permissibleTokenWithdrawal(toDispense));
require(ZTHTKN.transfer(_contract, toDispense));
emit DailyTokensSent(_contract, toDispense);
} else
{
// The contract in question has made a profit: retrieve the excess tokens.
uint toRetrieve = zthPresent.sub(dailyAmount);
require(ZTHTKN.transferFrom(_contract, address(this), toRetrieve));
emit DailyTokensReceived(_contract, toRetrieve);
}
emit DailyTokenAdmin(_contract);
}
// Dev withdrawal of tokens - splits equally among all owners of contract
function devTokenWithdraw(uint amount) public
onlyWallet
{
require(permissibleTokenWithdrawal(amount));
uint amountPerPerson = SafeMath.div(amount, owners.length);
for (uint i=0; i<owners.length; i++) {
ZTHTKN.transfer(owners[i], amountPerPerson);
}
emit DevWithdraw(amount, amountPerPerson);
}
// Change the dividend card address. Can't see why this would ever need
// to be invoked, but better safe than sorry.
function changeDivCardAddress(address _newDivCardAddress)
public
isAnOwner
{
divCardAddress = _newDivCardAddress;
}
// Receive Ether (from Zethr itself or any other source) and purchase tokens at the 33% dividend rate.
// If the amount is less than 0.01 Ether, the Ether is stored by the contract until the balance
// exceeds that limit and then purchases all it can.
function receiveDividends() public payable {
if (!reEntered) {
uint ActualBalance = (address(this).balance.sub(NonICOBuyins));
if (ActualBalance > 0.01 ether) {
reEntered = true;
ZTHTKN.buyAndSetDivPercentage.value(ActualBalance)(address(0x0), 33, "");
emit BankrollInvest(ActualBalance);
reEntered = false;
}
}
}
// Use all available balance to buy in
function buyInWithAllBalanced() public payable isAnOwner {
if (!reEntered) {
uint balance = address(this).balance;
require (balance > 0.01 ether);
ZTHTKN.buyAndSetDivPercentage.value(balance)(address(0x0), 33, "");
}
}
/*=================================
= UTILITIES =
=================================*/
// Convert an hexadecimal character to their value
function fromHexChar(uint c) public pure returns (uint) {
if (byte(c) >= byte('0') && byte(c) <= byte('9')) {
return c - uint(byte('0'));
}
if (byte(c) >= byte('a') && byte(c) <= byte('f')) {
return 10 + c - uint(byte('a'));
}
if (byte(c) >= byte('A') && byte(c) <= byte('F')) {
return 10 + c - uint(byte('A'));
}
}
// Convert an hexadecimal string to raw bytes
function fromHex(string s) public pure returns (bytes) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = byte(fromHexChar(uint(ss[2*i])) * 16 +
fromHexChar(uint(ss[2*i+1])));
}
return r;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint 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(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
} | Allows us to set the daily Token Limit | function setDailyTokenLimit(uint limit)
public
isAnOwner
{
dailyTknLimit = limit;
}
| 2,564,976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.