-
-
Save SashaFlores/00b0176e5d9662c5b932e96027594a7d to your computer and use it in GitHub Desktop.
Quest Crypto
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
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; | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
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); | |
function increaseAllowance(address spender, uint256 addedValue) 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 | |
); | |
} | |
abstract contract Context2 { | |
function _msgSender() internal view virtual returns (address) { | |
return msg.sender; | |
} | |
function _msgData() internal view virtual returns (bytes memory) { | |
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 | |
return msg.data; | |
} | |
} | |
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; | |
} | |
} | |
interface ITokenTracker{ | |
function increase(uint index,string memory refId,uint amount) external; | |
} | |
contract ICO is ReentrancyGuard,Context2{ | |
using SafeMath for uint256; | |
using SafeERC20 for IERC20; | |
address public usdcToken; | |
address public knabToken; | |
address public beneficiary; | |
uint256 constant START_TIME = 1623646591; | |
uint256 constant END_TIME = 1627603200; | |
uint256 ENDED = 0; | |
uint public _amountRaised; | |
uint public transferAmount; | |
uint public tokenSold=0; | |
uint public index; | |
address public tokenTracker; | |
event ICOInitialized(address beneficiary, uint256 timestamp); | |
event Buy(address indexed , uint256 amount, uint256 token ); | |
event amountRaisedUpdated(uint prevAmount,uint newAmount); | |
modifier onlyBeneficiary() { | |
require(_msgSender() == beneficiary, "Unauthorised access"); | |
_; | |
} | |
constructor( | |
address _tokenusdcAddress, | |
address _tokenknabAddress, | |
address _beneficiary, | |
address _tokenTracker, | |
uint _index | |
) { | |
require(_beneficiary !=address(0),"beneficiary address cannot be zero"); | |
usdcToken = (_tokenusdcAddress); | |
knabToken = (_tokenknabAddress); | |
beneficiary = _beneficiary; | |
index = _index; | |
tokenTracker=_tokenTracker; | |
emit ICOInitialized(_beneficiary, block.timestamp); | |
} | |
function calculateTransferAmount (uint ar , uint arn) internal view returns (uint) { | |
if(ar <10000000*(10**18)){ | |
if(arn>10000000*(10**18)) | |
{ | |
return (10000000*(10**18)-ar).mul(3).div(2).add(calculateTransferAmount(10000000*(10**18),arn)); | |
} | |
else{ | |
return arn.sub(ar).mul(3).div(2); | |
} | |
} | |
else if(ar >= 10000000*(10**18) && ar < 20000000*(10**18)){ | |
//return 7; | |
if(arn>20000000*(10**18)) | |
{ | |
return (20000000*(10**18)-ar).mul(7).div(5).add(calculateTransferAmount(20000000*(10**18),arn)); | |
} | |
else{ | |
return arn.sub(ar).mul(7).div(5); | |
} | |
} | |
else if(ar >= 20000000*(10**18) && ar < 30000000*(10**18)){ | |
///return 13; | |
if(arn>30000000*(10**18)) | |
{ | |
return (30000000*(10**18)-ar).mul(13).div(10).add(calculateTransferAmount(30000000*(10**18),arn)); | |
} | |
else{ | |
return arn.sub(ar).mul(13).div(10); | |
} | |
} | |
else if(ar >= 30000000*(10**18) && ar < 40000000*(10**18)){ | |
//return 12; | |
if(arn>40000000*(10**18)) | |
{ | |
return (40000000*(10**18)-ar).mul(12).div(10).add(calculateTransferAmount(40000000*(10**18),arn)); | |
} | |
else{ | |
return arn.sub(ar).mul(12).div(10); | |
} | |
} | |
else if(ar >= 40000000*(10**18) && ar <= 80000000*(10**18)){ | |
//return 23; | |
if(arn>80000000*(10**18)) | |
{ | |
return (80000000*(10**18)-ar).mul(115).div(100).add(calculateTransferAmount((80000000*(10**18))+1,arn)); | |
} | |
else{ | |
return arn.sub(ar).mul(115).div(100); | |
} | |
} | |
else { | |
//return 0; | |
return arn.sub(ar); | |
} | |
} | |
// function calculateRatiodenum () internal view returns (uint){ | |
// if(_amountRaised <=10000000*(10**18)){return 2;} | |
// else if(_amountRaised > 10000000*(10**18) && _amountRaised <= 20000000*(10**18)){return 5;} | |
// else if(_amountRaised > 20000000*(10**18) && _amountRaised <= 30000000*(10**18)){return 10;} | |
// else if(_amountRaised > 30000000*(10**18) && _amountRaised <= 40000000*(10**18)){return 10;} | |
// else if(_amountRaised > 40000000*(10**18) && _amountRaised <= 80000000*(10**18)){return 20;} | |
// else {return 1;} | |
// } | |
function KnabAmount(uint _amount)public view returns (uint){ | |
uint ar = _amountRaised; | |
uint arn = _amount.add(_amountRaised); | |
return calculateTransferAmount(ar,arn); | |
} | |
function details() public view returns (uint,uint){ | |
return (tokenSold,IERC20(knabToken).balanceOf(address(this))); | |
} | |
function buy(uint256 _amount,string memory refId) public nonReentrant { | |
require(ENDED==0,"ICO already ended"); | |
require(_amount>0,"_amount must be greater than 0"); | |
// calculate token amount to be created | |
uint ar = _amountRaised; | |
uint arn = _amount.add(_amountRaised); | |
transferAmount = calculateTransferAmount(ar,arn); | |
require(transferAmount<= IERC20(knabToken).balanceOf(address(this)),"!sufficient knab funds enter a lower value"); | |
emit Buy(_msgSender(), _amount, transferAmount); | |
require(IERC20(usdcToken).allowance(msg.sender,address(this))>0,"insufficient allowance of dai tokens"); | |
//transfer usdc token from user to contract | |
IERC20(usdcToken).safeTransferFrom(_msgSender(), address(this), _amount.div(10**12)); | |
//transfer knab token from contract to user | |
IERC20(knabToken).safeTransfer(_msgSender(), transferAmount); | |
tokenSold += transferAmount; | |
if(keccak256(abi.encodePacked(refId))!=keccak256(abi.encodePacked(""))){ | |
ITokenTracker(tokenTracker).increase(index, refId, transferAmount); | |
} | |
update(_amount); | |
} | |
function update (uint256 _Amount) internal{ | |
emit amountRaisedUpdated(_amountRaised,_amountRaised.add(_Amount)); | |
_amountRaised=_amountRaised.add(_Amount); | |
} | |
function fundTransfer(uint256 _amountTransfer) public onlyBeneficiary{ | |
require(_msgSender() !=address(0),"beneficiary address cannot be null"); | |
require(_amountTransfer>0,"transfer amount must be greater than 0"); | |
IERC20(usdcToken).safeTransfer(_msgSender(),_amountTransfer); | |
} | |
function crowdSaleEnd() public onlyBeneficiary{ | |
require(block.timestamp > END_TIME,"!!CrowdSale not Ended"); | |
ENDED=1; | |
} | |
function claimUnsold() public onlyBeneficiary{ | |
require(ENDED==1,'ICO not yet Ended'); | |
require(IERC20(knabToken).balanceOf(address(this)) != 0,"No KNAB is available to withdraw"); | |
IERC20(knabToken).safeTransfer(_msgSender(),IERC20(knabToken).balanceOf(address(this))); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; | |
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; | |
import "@openzeppelin/contracts/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 guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of ERC20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IERC20-approve}. | |
*/ | |
contract ERC20 is Context, IERC20, IERC20Metadata { | |
mapping (address => uint256) private _balances; | |
mapping (address => mapping (address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
/** | |
* @dev Sets the values for {name} and {symbol}. | |
* | |
* The defaut value of {decimals} is 18. To select a different value for | |
* {decimals} you should overload it. | |
* | |
* All two of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
constructor (string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the symbol of the token, usually a shorter version of the | |
* name. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the number of decimals used to get its user representation. | |
* For example, if `decimals` equals `2`, a balance of `505` tokens should | |
* be displayed to a user as `5,05` (`505 / 10 ** 2`). | |
* | |
* Tokens usually opt for a value of 18, imitating the relationship between | |
* Ether and Wei. This is the value {ERC20} uses, unless this function is | |
* overridden; | |
* | |
* NOTE: This information is only used for _display_ purposes: it in | |
* no way affects any of the arithmetic of the contract, including | |
* {IERC20-balanceOf} and {IERC20-transfer}. | |
*/ | |
function decimals() public view virtual override returns (uint8) { | |
return 18; | |
} | |
/** | |
* @dev See {IERC20-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {IERC20-balanceOf}. | |
*/ | |
function balanceOf(address account) public view virtual override returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {IERC20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public view virtual override returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {IERC20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public virtual override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {ERC20}. | |
* | |
* Requirements: | |
* | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for ``sender``'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(sender, recipient, amount); | |
uint256 currentAllowance = _allowances[sender][_msgSender()]; | |
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); | |
_approve(sender, _msgSender(), currentAllowance - amount); | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { | |
uint256 currentAllowance = _allowances[_msgSender()][spender]; | |
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); | |
_approve(_msgSender(), spender, currentAllowance - subtractedValue); | |
return true; | |
} | |
/** | |
* @dev Moves tokens `amount` from `sender` to `recipient`. | |
* | |
* This is internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer(address sender, address recipient, uint256 amount) internal virtual { | |
require(sender != address(0), "ERC20: transfer from the zero address"); | |
require(recipient != address(0), "ERC20: transfer to the zero address"); | |
_beforeTokenTransfer(sender, recipient, amount); | |
uint256 senderBalance = _balances[sender]; | |
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); | |
_balances[sender] = senderBalance - amount; | |
_balances[recipient] += amount; | |
emit Transfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal { | |
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 { } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.6.12; | |
import "./token/KnabrToken.sol"; | |
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" | |
); | |
} | |
} | |
} | |
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; | |
} | |
} | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) | |
private | |
view | |
returns (bool) | |
{ | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) | |
private | |
view | |
returns (bytes32) | |
{ | |
require( | |
set._values.length > index, | |
"EnumerableSet: index out of bounds" | |
); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) | |
internal | |
view | |
returns (bytes32) | |
{ | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) | |
internal | |
view | |
returns (address) | |
{ | |
return address(uint256(_at(set._inner, index))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) | |
internal | |
view | |
returns (uint256) | |
{ | |
return uint256(_at(set._inner, index)); | |
} | |
} | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred( | |
address indexed previousOwner, | |
address indexed newOwner | |
); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() internal { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(_owner == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = address(0); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require( | |
newOwner != address(0), | |
"Ownable: new owner is the zero address" | |
); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
interface IKNABR { | |
function mint(address _to, uint256 _amount) external; | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
// For interacting with our own strategy | |
interface IStrategy { | |
// Total want tokens managed by stratfegy | |
function wantLockedTotal() external view returns (uint256); | |
// Sum of all shares of users to wantLockedTotal | |
function sharesTotal() external view returns (uint256); | |
// Main want token compounding function | |
function earn() external; | |
// Transfer want tokens KNABRFarm -> strategy | |
function deposit(address _userAddress, uint256 _wantAmt) | |
external | |
returns (uint256); | |
function withdraw2(address _user, uint256 amount) external; | |
function withdrawloanall(address _user) external; | |
// Transfer want tokens strategy -> KNABRFarm | |
function withdraw(address _userAddress, uint256 _wantAmt) | |
external | |
returns (uint256); | |
function withdraw( | |
address _userAddress, | |
uint256 _wantAmt, | |
uint256 bamount | |
) external returns (uint256); | |
function inCaseTokensGetStuck( | |
address _token, | |
uint256 _amount, | |
address _to | |
) external; | |
} | |
contract KNABRFarm is Ownable, ReentrancyGuard { | |
using SafeMath for uint256; | |
using SafeERC20 for IERC20; | |
// Info of each user. | |
struct UserInfo { | |
uint256 shares; // How many LP tokens the user has provided. | |
uint256 rewardDebt; // Reward debt. | |
} | |
struct PoolInfo { | |
IERC20 want; // Address of the want token. | |
uint256 allocPoint; // How many allocation points assigned to this pool. KNABR to distribute per block. | |
uint256 lastRewardBlock; // Last block number that KNABR distribution occurs. | |
uint256 accKNABRPerShare; // Accumulated KNABR per share, times 1e12. See below. | |
address strat; // Strategy address that will KNABR compound want tokens | |
} | |
address public burnAddress = 0x000000000000000000000000000000000000dEaD; | |
address public KNABR; | |
uint256 public KNABRMaxSupply = 80000e18; | |
uint256 public KNABRPerBlock = 8000000000000000; // KnabR tokens created per block | |
uint256 public startBlock = 15792239; //https://polygonscan.com/blocks | |
PoolInfo[] public poolInfo; // Info of each pool. | |
mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens. | |
uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools. | |
event Deposit(address indexed user, uint256 indexed pid, uint256 amount); | |
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); | |
event EmergencyWithdraw( | |
address indexed user, | |
uint256 indexed pid, | |
uint256 amount | |
); | |
constructor() public { | |
KNABR = address(new KnabrToken()); | |
} | |
function poolLength() external view returns (uint256) { | |
return poolInfo.length; | |
} | |
// Add a new lp to the pool. Can only be called by the owner. | |
function add( | |
uint256 _allocPoint, | |
IERC20 _want, | |
bool _withUpdate, | |
address _strat | |
) public onlyOwner { | |
if (_withUpdate) { | |
massUpdatePools(); | |
} | |
uint256 lastRewardBlock = block.number > startBlock | |
? block.number | |
: startBlock; | |
totalAllocPoint = totalAllocPoint.add(_allocPoint); | |
poolInfo.push( | |
PoolInfo({ | |
want: _want, | |
allocPoint: _allocPoint, | |
lastRewardBlock: lastRewardBlock, | |
accKNABRPerShare: 0, | |
strat: _strat | |
}) | |
); | |
} | |
// Update the given pool's allocation point. Can only be called by the owner. | |
function set( | |
uint256 _pid, | |
uint256 _allocPoint, | |
bool _withUpdate | |
) public onlyOwner { | |
if (_withUpdate) { | |
massUpdatePools(); | |
} | |
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( | |
_allocPoint | |
); | |
poolInfo[_pid].allocPoint = _allocPoint; | |
} | |
// Return reward multiplier over the given _from to _to block. | |
function getMultiplier(uint256 _from, uint256 _to) | |
public | |
view | |
returns (uint256) | |
{ | |
if (IERC20(KNABR).totalSupply() >= KNABRMaxSupply) { | |
return 0; | |
} | |
return _to.sub(_from); | |
} | |
// View function to see pending KNABR on frontend. | |
function pendingKNABR(uint256 _pid, address _user) | |
external | |
view | |
returns (uint256) | |
{ | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][_user]; | |
uint256 accKNABRPerShare = pool.accKNABRPerShare; | |
uint256 sharesTotal = IStrategy(pool.strat).sharesTotal(); | |
if (block.number > pool.lastRewardBlock && sharesTotal != 0) { | |
uint256 multiplier = getMultiplier( | |
pool.lastRewardBlock, | |
block.number | |
); | |
uint256 KNABReward = multiplier | |
.mul(KNABRPerBlock) | |
.mul(pool.allocPoint) | |
.div(totalAllocPoint); | |
accKNABRPerShare = accKNABRPerShare.add( | |
KNABReward.mul(1e12).div(sharesTotal) | |
); | |
} | |
return user.shares.mul(accKNABRPerShare).div(1e12).sub(user.rewardDebt); | |
} | |
// View function to see staked Want tokens on frontend. | |
function stakedWantTokens(uint256 _pid, address _user) | |
external | |
view | |
returns (uint256) | |
{ | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][_user]; | |
uint256 sharesTotal = IStrategy(pool.strat).sharesTotal(); | |
uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strat) | |
.wantLockedTotal(); | |
if (sharesTotal == 0) { | |
return 0; | |
} | |
return user.shares.mul(wantLockedTotal).div(sharesTotal); | |
} | |
// Update reward variables for all pools. Be careful of gas spending! | |
function massUpdatePools() public { | |
uint256 length = poolInfo.length; | |
for (uint256 pid = 0; pid < length; ++pid) { | |
updatePool(pid); | |
} | |
} | |
// Update reward variables of the given pool to be up-to-date. | |
function updatePool(uint256 _pid) public { | |
PoolInfo storage pool = poolInfo[_pid]; | |
if (block.number <= pool.lastRewardBlock) { | |
return; | |
} | |
uint256 sharesTotal = IStrategy(pool.strat).sharesTotal(); | |
if (sharesTotal == 0) { | |
pool.lastRewardBlock = block.number; | |
return; | |
} | |
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); | |
if (multiplier <= 0) { | |
return; | |
} | |
uint256 KNABReward = multiplier | |
.mul(KNABRPerBlock) | |
.mul(pool.allocPoint) | |
.div(totalAllocPoint); | |
IKNABR(KNABR).mint(address(this), KNABReward); | |
pool.accKNABRPerShare = pool.accKNABRPerShare.add( | |
KNABReward.mul(1e12).div(sharesTotal) | |
); | |
pool.lastRewardBlock = block.number; | |
} | |
// Want tokens moved from user -> KNABRFarm (KNABR allocation) -> Strat (compounding) | |
function deposit(uint256 _pid, uint256 _wantAmt) public nonReentrant { | |
updatePool(_pid); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
if (user.shares > 0) { | |
uint256 pending = user | |
.shares | |
.mul(pool.accKNABRPerShare) | |
.div(1e12) | |
.sub(user.rewardDebt); | |
if (pending > 0) { | |
safeKNABRTransfer(msg.sender, pending); | |
} | |
} | |
if (_wantAmt > 0) { | |
pool.want.safeTransferFrom( | |
address(msg.sender), | |
address(this), | |
_wantAmt | |
); | |
pool.want.safeIncreaseAllowance(pool.strat, _wantAmt); | |
uint256 sharesAdded = IStrategy(poolInfo[_pid].strat).deposit( | |
msg.sender, | |
_wantAmt | |
); | |
user.shares = user.shares.add(sharesAdded); | |
} | |
user.rewardDebt = user.shares.mul(pool.accKNABRPerShare).div(1e12); | |
emit Deposit(msg.sender, _pid, _wantAmt); | |
} | |
// Withdraw LP tokens from pool. | |
function withdraw(uint256 _pid, uint256 _wantAmt) public nonReentrant { | |
updatePool(_pid); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strat) | |
.wantLockedTotal(); | |
uint256 sharesTotal = IStrategy(poolInfo[_pid].strat).sharesTotal(); | |
require(user.shares > 0, "user.shares is 0"); | |
require(sharesTotal > 0, "sharesTotal is 0"); | |
// Withdraw pending KNABR | |
uint256 pending = user.shares.mul(pool.accKNABRPerShare).div(1e12).sub( | |
user.rewardDebt | |
); | |
if (pending > 0) { | |
safeKNABRTransfer(msg.sender, pending); | |
} | |
// Withdraw want tokens | |
uint256 amount = user.shares.mul(wantLockedTotal).div(sharesTotal); | |
if (_wantAmt > amount) { | |
_wantAmt = amount; | |
} | |
if (_wantAmt > 0) { | |
uint256 sharesRemoved = IStrategy(poolInfo[_pid].strat).withdraw( | |
msg.sender, | |
_wantAmt | |
); | |
if (sharesRemoved > user.shares) { | |
user.shares = 0; | |
} else { | |
user.shares = user.shares.sub(sharesRemoved); | |
} | |
uint256 wantBal = IERC20(pool.want).balanceOf(address(this)); | |
if (wantBal < _wantAmt) { | |
_wantAmt = wantBal; | |
} | |
pool.want.safeTransfer(address(msg.sender), _wantAmt); | |
} | |
user.rewardDebt = user.shares.mul(pool.accKNABRPerShare).div(1e12); | |
emit Withdraw(msg.sender, _pid, _wantAmt); | |
} | |
//withdrawal function for aaveStrategy | |
function withdraw2( | |
uint256 _pid, | |
uint256 _wantAmt, | |
uint256 bamount | |
) public nonReentrant { | |
updatePool(_pid); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
uint256 wantLockedTotal = IStrategy(poolInfo[_pid].strat) | |
.wantLockedTotal(); | |
uint256 sharesTotal = IStrategy(poolInfo[_pid].strat).sharesTotal(); | |
require(user.shares > 0, "user.shares is 0"); | |
require(sharesTotal > 0, "sharesTotal is 0"); | |
// Withdraw pending KNABR | |
uint256 pending = user.shares.mul(pool.accKNABRPerShare).div(1e12).sub( | |
user.rewardDebt | |
); | |
if (pending > 0) { | |
safeKNABRTransfer(msg.sender, pending); | |
} | |
// Withdraw want tokens | |
uint256 amount = user.shares.mul(wantLockedTotal).div(sharesTotal); | |
if (_wantAmt > amount) { | |
_wantAmt = amount; | |
} | |
if (_wantAmt > 0) { | |
uint256 sharesRemoved = IStrategy(poolInfo[_pid].strat).withdraw( | |
msg.sender, | |
_wantAmt, | |
bamount | |
); | |
if (sharesRemoved > user.shares) { | |
user.shares = 0; | |
} else { | |
user.shares = user.shares.sub(sharesRemoved); | |
} | |
uint256 wantBal = IERC20(pool.want).balanceOf(address(this)); | |
if (wantBal < _wantAmt) { | |
_wantAmt = wantBal; | |
} | |
pool.want.safeTransfer(address(msg.sender), _wantAmt); | |
} | |
user.rewardDebt = user.shares.mul(pool.accKNABRPerShare).div(1e12); | |
emit Withdraw(msg.sender, _pid, _wantAmt); | |
} | |
function harvestKNABR(uint256 _pid) public { | |
updatePool(_pid); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
uint256 sharesTotal = IStrategy(poolInfo[_pid].strat).sharesTotal(); | |
if (user.shares > 0 && sharesTotal > 0) { | |
uint256 pending = user | |
.shares | |
.mul(pool.accKNABRPerShare) | |
.div(1e12) | |
.sub(user.rewardDebt); | |
if (pending > 0) { | |
safeKNABRTransfer(msg.sender, pending); | |
} | |
user.rewardDebt = user.shares.mul(pool.accKNABRPerShare).div(1e12); | |
} | |
} | |
function withdrawAll(uint256 _pid) public { | |
withdraw(_pid, uint256(-1)); | |
} | |
function withdrawLoan(uint256 _pid, uint256 amount) public nonReentrant { | |
IStrategy(poolInfo[_pid].strat).withdraw2(msg.sender, amount); | |
} | |
function withdrawLoanAll(uint256 _pid) public nonReentrant { | |
IStrategy(poolInfo[_pid].strat).withdrawloanall(msg.sender); | |
} | |
function calculatePartition(uint256 _pid, address _strat) | |
public | |
view | |
returns (uint256) | |
{ | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
uint256 sharesTotal = IStrategy(poolInfo[_pid].strat).sharesTotal(); | |
return | |
IStrategy(_strat).wantLockedTotal().mul(user.shares).div( | |
sharesTotal | |
); | |
} | |
// Withdraw without caring about rewards. EMERGENCY ONLY. | |
// function emergencyWithdraw(uint256 _pid) public nonReentrant { | |
// PoolInfo storage pool = poolInfo[_pid]; | |
// UserInfo storage user = userInfo[_pid][msg.sender]; | |
// uint256 wantLockedTotal = | |
// IStrategy(poolInfo[_pid].strat).wantLockedTotal(); | |
// uint256 sharesTotal = IStrategy(poolInfo[_pid].strat).sharesTotal(); | |
// uint256 amount = user.shares.mul(wantLockedTotal).div(sharesTotal); | |
// IStrategy(poolInfo[_pid].strat).withdraw(msg.sender, amount); | |
// pool.want.safeTransfer(address(msg.sender), amount); | |
// emit EmergencyWithdraw(msg.sender, _pid, amount); | |
// user.shares = 0; | |
// user.rewardDebt = 0; | |
// } | |
// Safe KNABR transfer function, just in case if rounding error causes pool to not have enough | |
function safeKNABRTransfer(address _to, uint256 _KNABRAmt) internal { | |
uint256 KNABRBal = IERC20(KNABR).balanceOf(address(this)); | |
if (_KNABRAmt > KNABRBal) { | |
IERC20(KNABR).transfer(_to, KNABRBal); | |
} else { | |
IERC20(KNABR).transfer(_to, _KNABRAmt); | |
} | |
} | |
function inCaseTokensGetStuck(address _token, uint256 _amount) | |
public | |
onlyOwner | |
{ | |
require(_token != KNABR, "!safe"); | |
IERC20(_token).safeTransfer(msg.sender, _amount); | |
} | |
// function migrateToKnab(uint256 _inputAmt) public { | |
// require(block.number < 5033333, "too late :("); | |
// IERC20(KNABR).safeIncreaseAllowance(burnAddress, _inputAmt); | |
// IERC20(KNABR).safeTransferFrom( | |
// address(msg.sender), | |
// burnAddress, | |
// _inputAmt | |
// ); | |
// IKNABR(KNABR).mint(msg.sender, _inputAmt); | |
// } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
interface IERC20 { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} | |
interface IERC20Metadata is IERC20 { | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() external view returns (string memory); | |
/** | |
* @dev Returns the symbol of the token. | |
*/ | |
function symbol() external view returns (string memory); | |
/** | |
* @dev Returns the decimals places of the token. | |
*/ | |
function decimals() external view returns (uint8); | |
} | |
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; | |
} | |
} | |
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; | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
/** | |
* @dev Implementation of the {IERC20} interface. | |
* | |
* This implementation is agnostic to the way tokens are created. This means | |
* that a supply mechanism has to be added in a derived contract using {_mint}. | |
* For a generic mechanism see {ERC20PresetMinterPauser}. | |
* | |
* TIP: For a detailed writeup see our guide | |
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How | |
* to implement supply mechanisms]. | |
* | |
* We have followed general OpenZeppelin guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of ERC20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IERC20-approve}. | |
*/ | |
contract ERC20 is Context, IERC20, IERC20Metadata { | |
mapping (address => uint256) private _balances; | |
mapping (address => mapping (address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
/** | |
* @dev Sets the values for {name} and {symbol}. | |
* | |
* The defaut value of {decimals} is 18. To select a different value for | |
* {decimals} you should overload it. | |
* | |
* All two of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
constructor (string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the symbol of the token, usually a shorter version of the | |
* name. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the number of decimals used to get its user representation. | |
* For example, if `decimals` equals `2`, a balance of `505` tokens should | |
* be displayed to a user as `5,05` (`505 / 10 ** 2`). | |
* | |
* Tokens usually opt for a value of 18, imitating the relationship between | |
* Ether and Wei. This is the value {ERC20} uses, unless this function is | |
* overridden; | |
* | |
* NOTE: This information is only used for _display_ purposes: it in | |
* no way affects any of the arithmetic of the contract, including | |
* {IERC20-balanceOf} and {IERC20-transfer}. | |
*/ | |
function decimals() public view virtual override returns (uint8) { | |
return 18; | |
} | |
/** | |
* @dev See {IERC20-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {IERC20-balanceOf}. | |
*/ | |
function balanceOf(address account) public view virtual override returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {IERC20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public view virtual override returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {IERC20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public virtual override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {ERC20}. | |
* | |
* Requirements: | |
* | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for ``sender``'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(sender, recipient, amount); | |
uint256 currentAllowance = _allowances[sender][_msgSender()]; | |
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); | |
_approve(sender, _msgSender(), currentAllowance - amount); | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { | |
uint256 currentAllowance = _allowances[_msgSender()][spender]; | |
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); | |
_approve(_msgSender(), spender, currentAllowance - subtractedValue); | |
return true; | |
} | |
/** | |
* @dev Moves tokens `amount` from `sender` to `recipient`. | |
* | |
* This is internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer(address sender, address recipient, uint256 amount) internal virtual { | |
require(sender != address(0), "ERC20: transfer from the zero address"); | |
require(recipient != address(0), "ERC20: transfer to the zero address"); | |
_beforeTokenTransfer(sender, recipient, amount); | |
uint256 senderBalance = _balances[sender]; | |
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); | |
_balances[sender] = senderBalance - amount; | |
_balances[recipient] += amount; | |
emit Transfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal { | |
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 { } | |
} | |
contract KnabToken is ERC20 { | |
address owner; | |
using SafeERC20 for IERC20; | |
constructor() ERC20("Knab","KNAB"){ | |
require(_msgSender() !=address(0),"owner's address cannot be null"); | |
owner = _msgSender(); | |
_mint(address(this),1000000000*(10**18)); //1B | |
} | |
function transferKnab(address _ad, uint _amt ) public { | |
require(msg.sender==owner); | |
IERC20(address(this)).safeTransfer(_ad,_amt); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
interface IERC20 { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} | |
interface IERC20Metadata is IERC20 { | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() external view returns (string memory); | |
/** | |
* @dev Returns the symbol of the token. | |
*/ | |
function symbol() external view returns (string memory); | |
/** | |
* @dev Returns the decimals places of the token. | |
*/ | |
function decimals() external view returns (uint8); | |
} | |
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; | |
} | |
} | |
/** | |
* @dev Implementation of the {IERC20} interface. | |
* | |
* This implementation is agnostic to the way tokens are created. This means | |
* that a supply mechanism has to be added in a derived contract using {_mint}. | |
* For a generic mechanism see {ERC20PresetMinterPauser}. | |
* | |
* TIP: For a detailed writeup see our guide | |
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How | |
* to implement supply mechanisms]. | |
* | |
* We have followed general OpenZeppelin guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of ERC20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IERC20-approve}. | |
*/ | |
contract ERC20 is Context, IERC20, IERC20Metadata { | |
mapping (address => uint256) private _balances; | |
mapping (address => mapping (address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
/** | |
* @dev Sets the values for {name} and {symbol}. | |
* | |
* The defaut value of {decimals} is 18. To select a different value for | |
* {decimals} you should overload it. | |
* | |
* All two of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
constructor (string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the symbol of the token, usually a shorter version of the | |
* name. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the number of decimals used to get its user representation. | |
* For example, if `decimals` equals `2`, a balance of `505` tokens should | |
* be displayed to a user as `5,05` (`505 / 10 ** 2`). | |
* | |
* Tokens usually opt for a value of 18, imitating the relationship between | |
* Ether and Wei. This is the value {ERC20} uses, unless this function is | |
* overridden; | |
* | |
* NOTE: This information is only used for _display_ purposes: it in | |
* no way affects any of the arithmetic of the contract, including | |
* {IERC20-balanceOf} and {IERC20-transfer}. | |
*/ | |
function decimals() public view virtual override returns (uint8) { | |
return 18; | |
} | |
/** | |
* @dev See {IERC20-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {IERC20-balanceOf}. | |
*/ | |
function balanceOf(address account) public view virtual override returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {IERC20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public view virtual override returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {IERC20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public virtual override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {ERC20}. | |
* | |
* Requirements: | |
* | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for ``sender``'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(sender, recipient, amount); | |
uint256 currentAllowance = _allowances[sender][_msgSender()]; | |
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); | |
_approve(sender, _msgSender(), currentAllowance - amount); | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { | |
uint256 currentAllowance = _allowances[_msgSender()][spender]; | |
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); | |
_approve(_msgSender(), spender, currentAllowance - subtractedValue); | |
return true; | |
} | |
/** | |
* @dev Moves tokens `amount` from `sender` to `recipient`. | |
* | |
* This is internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer(address sender, address recipient, uint256 amount) internal virtual { | |
require(sender != address(0), "ERC20: transfer from the zero address"); | |
require(recipient != address(0), "ERC20: transfer to the zero address"); | |
_beforeTokenTransfer(sender, recipient, amount); | |
uint256 senderBalance = _balances[sender]; | |
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); | |
_balances[sender] = senderBalance - amount; | |
_balances[recipient] += amount; | |
emit Transfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal { | |
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 { } | |
} | |
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); | |
} | |
} | |
} | |
} | |
/** | |
* @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"); | |
} | |
} | |
} | |
interface ITokenTracker{ | |
function increase(uint index,string memory refId,uint amount) external; | |
} | |
contract QuestToken is ERC20 { | |
address SCAddress; | |
using SafeERC20 for IERC20; | |
uint public index; | |
address public tokentracker; | |
constructor(address sca,uint _index,address _tokenTracker) ERC20("quest", "QUEST") { | |
require(_msgSender() != address(0), "owner's address cannot be null"); | |
SCAddress = sca; | |
index = _index; | |
tokentracker = _tokenTracker; | |
} | |
function buyQST(uint amount ,string memory refId) public{ | |
require(amount>0,"_amount must be greater than 0"); | |
IERC20(SCAddress).transferFrom(msg.sender,address(this),amount); | |
_mint(msg.sender,amount*10**12); | |
ITokenTracker(tokentracker).increase(index, refId, amount*10**12); | |
} | |
function returnQST(uint amount) public { | |
require(amount>0,"_amount must be greater than 0"); | |
_burn(msg.sender, amount*10**12); | |
IERC20(SCAddress).safeTransfer(msg.sender, amount); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.6.12; | |
interface IERC20 { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} | |
library 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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
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; | |
} | |
} | |
pragma solidity 0.6.12; | |
// "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol"; | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
contract rewards is ReentrancyGuard{ | |
using SafeERC20 for IERC20; | |
using SafeMath for uint; | |
uint public totalDeposit; | |
uint public endTime; | |
uint public claimEndTime; | |
IERC20 KNABR; | |
IERC20 Knab; | |
address public owner; | |
mapping(address => uint) public userDeposit; | |
uint startTime; | |
constructor (address _knabr, address _knab, uint _endTime,uint _claimEndTime) public { | |
KNABR = IERC20(_knabr); | |
Knab = IERC20(_knab); | |
startTime = block.timestamp; | |
endTime = block.timestamp.add(_endTime); | |
claimEndTime = block.timestamp.add(_claimEndTime); | |
owner = msg.sender; | |
} | |
function deposit (uint amount) public nonReentrant { | |
require(block.timestamp>startTime); | |
require(block.timestamp<endTime); | |
KNABR.safeTransferFrom(msg.sender, address(this), amount); | |
totalDeposit += amount; | |
userDeposit[msg.sender] += amount; | |
} | |
function claimRewards () public nonReentrant{ | |
require(userDeposit[msg.sender]>0,'You dont own enough shares'); | |
require(block.timestamp> endTime); | |
uint balance = Knab.balanceOf(address(this)); | |
uint userShare = balance.mul(userDeposit[msg.sender]).div(totalDeposit); | |
Knab.safeTransfer(msg.sender, userShare); | |
totalDeposit= totalDeposit.sub(userDeposit[msg.sender]); | |
userDeposit[msg.sender] = 0; | |
} | |
function getKnab () public view returns(uint){ | |
uint balance = Knab.balanceOf(address(this)); | |
uint userShare = balance.mul(userDeposit[msg.sender]).div(totalDeposit); | |
return userShare; | |
} | |
function inCaseTokensAreStuck() public { | |
require(msg.sender == owner,'Not authorised'); | |
require(block.timestamp>claimEndTime,'Please Wait till the time ends'); | |
Knab.safeTransfer(msg.sender, Knab.balanceOf(address(this))); | |
} | |
function changeOwner(address owner2) public { | |
require(msg.sender == owner,'Not authorised'); | |
owner = owner2; | |
} | |
function getStatus() public view returns(uint) { | |
if(block.timestamp> endTime){ | |
return 1; | |
} | |
else return 0; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.6.12; | |
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); | |
function decimals() external view returns (uint8); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) | |
external | |
returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) | |
external | |
view | |
returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval( | |
address indexed owner, | |
address indexed spender, | |
uint256 value | |
); | |
} | |
library SafeMath { | |
/** | |
* @dev Returns the addition of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `+` operator. | |
* | |
* Requirements: | |
* | |
* - Addition cannot overflow. | |
*/ | |
function add(uint256 a, uint256 b) internal pure returns (uint256) { | |
uint256 c = a + b; | |
require(c >= a, "SafeMath: addition overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub(uint256 a, uint256 b) internal pure returns (uint256) { | |
return sub(a, b, "SafeMath: subtraction overflow"); | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b <= a, errorMessage); | |
uint256 c = a - b; | |
return c; | |
} | |
/** | |
* @dev Returns the multiplication of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `*` operator. | |
* | |
* Requirements: | |
* | |
* - Multiplication cannot overflow. | |
*/ | |
function mul(uint256 a, uint256 b) internal pure returns (uint256) { | |
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the | |
// benefit is lost if 'b' is also tested. | |
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | |
if (a == 0) { | |
return 0; | |
} | |
uint256 c = a * b; | |
require(c / a == b, "SafeMath: multiplication overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div(uint256 a, uint256 b) internal pure returns (uint256) { | |
return div(a, b, "SafeMath: division by zero"); | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b > 0, errorMessage); | |
uint256 c = a / b; | |
// assert(a == b * c + a % b); // There is no case in which this doesn't hold | |
return c; | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod(uint256 a, uint256 b) internal pure returns (uint256) { | |
return mod(a, b, "SafeMath: modulo by zero"); | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts with custom message when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b != 0, errorMessage); | |
return a % b; | |
} | |
} | |
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; | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) | |
private | |
view | |
returns (bool) | |
{ | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) | |
private | |
view | |
returns (bytes32) | |
{ | |
require( | |
set._values.length > index, | |
"EnumerableSet: index out of bounds" | |
); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) | |
internal | |
view | |
returns (bytes32) | |
{ | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) | |
internal | |
view | |
returns (address) | |
{ | |
return address(uint256(_at(set._inner, index))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) | |
internal | |
view | |
returns (uint256) | |
{ | |
return uint256(_at(set._inner, index)); | |
} | |
} | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred( | |
address indexed previousOwner, | |
address indexed newOwner | |
); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() internal { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(_owner == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = address(0); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require( | |
newOwner != address(0), | |
"Ownable: new owner is the zero address" | |
); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
contract Pausable is Context { | |
/** | |
* @dev Emitted when the pause is triggered by `account`. | |
*/ | |
event Paused(address account); | |
/** | |
* @dev Emitted when the pause is lifted by `account`. | |
*/ | |
event Unpaused(address account); | |
bool private _paused; | |
/** | |
* @dev Initializes the contract in unpaused state. | |
*/ | |
constructor() internal { | |
_paused = false; | |
} | |
/** | |
* @dev Returns true if the contract is paused, and false otherwise. | |
*/ | |
function paused() public view returns (bool) { | |
return _paused; | |
} | |
/** | |
* @dev Modifier to make a function callable only when the contract is not paused. | |
* | |
* 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()); | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
abstract contract StratX2 is Ownable, ReentrancyGuard, Pausable { | |
// Maximises yields in pancakeswap | |
using SafeMath for uint256; | |
using SafeERC20 for IERC20; | |
address public wantAddress; | |
address public KNABRFarmAddress; | |
address public KNABaddress; | |
address public govAddress; // timelock contract | |
bool public onlyGov1 = true; | |
uint256 public wantLockedTotal = 0; | |
uint256 public sharesTotal = 0; | |
event SetGov(address _govAddress); | |
event SetOnlyGov(bool _onlyGov1); | |
modifier onlyAllowGov() { | |
require(msg.sender == govAddress, "!gov"); | |
_; | |
} | |
function pause() public virtual onlyAllowGov { | |
_pause(); | |
} | |
function unpause() public virtual onlyAllowGov { | |
_unpause(); | |
} | |
function setGov(address _govAddress) public virtual onlyAllowGov { | |
govAddress = _govAddress; | |
emit SetGov(_govAddress); | |
} | |
function setOnlyGov(bool _onlyGov1) public virtual onlyAllowGov { | |
onlyGov1 = _onlyGov1; | |
emit SetOnlyGov(_onlyGov1); | |
} | |
function inCaseTokensGetStuck( | |
address _token, | |
uint256 _amount, | |
address _to | |
) public virtual onlyAllowGov { | |
require(_token != wantAddress, "!safe"); | |
IERC20(_token).safeTransfer(_to, _amount); | |
} | |
} | |
contract StratX2_KNAB is StratX2 { | |
address[] public users; | |
mapping(address => uint256) public userLastDepositedTimestamp; | |
uint256 public minTimeToWithdraw; // 604800 = 1 week | |
uint256 public minTimeToWithdrawUL = 1209600; // 2 weeks | |
event minTimeToWithdrawChanged( | |
uint256 oldMinTimeToWithdraw, | |
uint256 newMinTimeToWithdraw | |
); | |
event earned(uint256 oldWantLockedTotal, uint256 newWantLockedTotal); | |
constructor( | |
address[] memory _addresses, | |
uint256 _minTimeToWithdraw | |
) public { | |
govAddress = _addresses[0]; | |
KNABRFarmAddress = _addresses[1]; | |
KNABaddress = _addresses[2]; | |
wantAddress = _addresses[3]; | |
minTimeToWithdraw = _minTimeToWithdraw; | |
transferOwnership(KNABRFarmAddress); | |
} | |
function deposit(address _userAddress, uint256 _wantAmt) | |
public | |
onlyOwner | |
nonReentrant | |
whenNotPaused | |
returns (uint256) | |
{ | |
if (userLastDepositedTimestamp[_userAddress] == 0) { | |
users.push(_userAddress); | |
} | |
userLastDepositedTimestamp[_userAddress] = block.timestamp; | |
IERC20(wantAddress).safeTransferFrom( | |
address(msg.sender), | |
address(this), | |
_wantAmt | |
); | |
uint256 sharesAdded = _wantAmt; | |
sharesTotal = sharesTotal.add(sharesAdded); | |
wantLockedTotal = IERC20(KNABaddress).balanceOf(address(this)); | |
return sharesAdded; | |
} | |
function withdraw(address _userAddress, uint256 _wantAmt) | |
public | |
onlyOwner | |
nonReentrant | |
returns (uint256) | |
{ | |
require( | |
(userLastDepositedTimestamp[_userAddress].add(minTimeToWithdraw)) < | |
block.timestamp, | |
"too early!" | |
); | |
require(_wantAmt > 0, "_wantAmt <= 0"); | |
uint256 sharesRemoved = _wantAmt.mul(sharesTotal).div(wantLockedTotal); | |
if (sharesRemoved > sharesTotal) { | |
sharesRemoved = sharesTotal; | |
} | |
sharesTotal = sharesTotal.sub(sharesRemoved); | |
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); | |
if (_wantAmt > wantAmt) { | |
_wantAmt = wantAmt; | |
} | |
if (wantLockedTotal < _wantAmt) { | |
_wantAmt = wantLockedTotal; | |
} | |
wantLockedTotal = wantLockedTotal.sub(_wantAmt); | |
IERC20(wantAddress).safeTransfer(KNABRFarmAddress, _wantAmt); | |
return sharesRemoved; | |
} | |
function _farm() internal {} | |
function _unfarm(uint256 _wantAmt) internal {} | |
function earn() public nonReentrant whenNotPaused { | |
if (onlyGov1) { | |
require(msg.sender == govAddress, "!gov"); | |
} | |
} | |
function setMinTimeToWithdraw(uint256 newMinTimeToWithdraw) | |
public | |
onlyAllowGov | |
{ | |
require(newMinTimeToWithdraw <= minTimeToWithdrawUL, "too high"); | |
emit minTimeToWithdrawChanged(minTimeToWithdraw, newMinTimeToWithdraw); | |
minTimeToWithdraw = newMinTimeToWithdraw; | |
} | |
function userLength() public view returns (uint256) { | |
return users.length; | |
} | |
receive() external payable {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.6.12; | |
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); | |
function decimals() external view returns (uint8); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) | |
external | |
returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) | |
external | |
view | |
returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval( | |
address indexed owner, | |
address indexed spender, | |
uint256 value | |
); | |
} | |
library SafeMath { | |
/** | |
* @dev Returns the addition of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `+` operator. | |
* | |
* Requirements: | |
* | |
* - Addition cannot overflow. | |
*/ | |
function add(uint256 a, uint256 b) internal pure returns (uint256) { | |
uint256 c = a + b; | |
require(c >= a, "SafeMath: addition overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub(uint256 a, uint256 b) internal pure returns (uint256) { | |
return sub(a, b, "SafeMath: subtraction overflow"); | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b <= a, errorMessage); | |
uint256 c = a - b; | |
return c; | |
} | |
/** | |
* @dev Returns the multiplication of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `*` operator. | |
* | |
* Requirements: | |
* | |
* - Multiplication cannot overflow. | |
*/ | |
function mul(uint256 a, uint256 b) internal pure returns (uint256) { | |
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the | |
// benefit is lost if 'b' is also tested. | |
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | |
if (a == 0) { | |
return 0; | |
} | |
uint256 c = a * b; | |
require(c / a == b, "SafeMath: multiplication overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div(uint256 a, uint256 b) internal pure returns (uint256) { | |
return div(a, b, "SafeMath: division by zero"); | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b > 0, errorMessage); | |
uint256 c = a / b; | |
// assert(a == b * c + a % b); // There is no case in which this doesn't hold | |
return c; | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod(uint256 a, uint256 b) internal pure returns (uint256) { | |
return mod(a, b, "SafeMath: modulo by zero"); | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts with custom message when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b != 0, errorMessage); | |
return a % b; | |
} | |
} | |
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; | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) | |
private | |
view | |
returns (bool) | |
{ | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) | |
private | |
view | |
returns (bytes32) | |
{ | |
require( | |
set._values.length > index, | |
"EnumerableSet: index out of bounds" | |
); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) | |
internal | |
view | |
returns (bytes32) | |
{ | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) | |
internal | |
view | |
returns (address) | |
{ | |
return address(uint256(_at(set._inner, index))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) | |
internal | |
view | |
returns (uint256) | |
{ | |
return uint256(_at(set._inner, index)); | |
} | |
} | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred( | |
address indexed previousOwner, | |
address indexed newOwner | |
); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() internal { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(_owner == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = address(0); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require( | |
newOwner != address(0), | |
"Ownable: new owner is the zero address" | |
); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
contract Pausable is Context { | |
/** | |
* @dev Emitted when the pause is triggered by `account`. | |
*/ | |
event Paused(address account); | |
/** | |
* @dev Emitted when the pause is lifted by `account`. | |
*/ | |
event Unpaused(address account); | |
bool private _paused; | |
/** | |
* @dev Initializes the contract in unpaused state. | |
*/ | |
constructor() internal { | |
_paused = false; | |
} | |
/** | |
* @dev Returns true if the contract is paused, and false otherwise. | |
*/ | |
function paused() public view returns (bool) { | |
return _paused; | |
} | |
/** | |
* @dev Modifier to make a function callable only when the contract is not paused. | |
* | |
* 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()); | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
abstract contract StratX2 is Ownable, ReentrancyGuard, Pausable { | |
// Maximises yields in pancakeswap | |
using SafeMath for uint256; | |
using SafeERC20 for IERC20; | |
address public wantAddress; | |
address public KNABRFarmAddress; | |
address public LPaddress; | |
address public govAddress; // timelock contract | |
bool public onlyGov1 = true; | |
uint256 public wantLockedTotal = 0; | |
uint256 public sharesTotal = 0; | |
event SetGov(address _govAddress); | |
event SetOnlyGov(bool _onlyGov1); | |
modifier onlyAllowGov() { | |
require(msg.sender == govAddress, "!gov"); | |
_; | |
} | |
function pause() public virtual onlyAllowGov { | |
_pause(); | |
} | |
function unpause() public virtual onlyAllowGov { | |
_unpause(); | |
} | |
function setGov(address _govAddress) public virtual onlyAllowGov { | |
govAddress = _govAddress; | |
emit SetGov(_govAddress); | |
} | |
function setOnlyGov(bool _onlyGov1) public virtual onlyAllowGov { | |
onlyGov1 = _onlyGov1; | |
emit SetOnlyGov(_onlyGov1); | |
} | |
function inCaseTokensGetStuck( | |
address _token, | |
uint256 _amount, | |
address _to | |
) public virtual onlyAllowGov { | |
require(_token != wantAddress, "!safe"); | |
IERC20(_token).safeTransfer(_to, _amount); | |
} | |
} | |
contract StratX2_LP is StratX2 { | |
address[] public users; | |
mapping(address => uint256) public userLastDepositedTimestamp; | |
uint256 public minTimeToWithdraw; // 604800 = 1 week | |
uint256 public minTimeToWithdrawUL = 1209600; // 2 weeks | |
event minTimeToWithdrawChanged( | |
uint256 oldMinTimeToWithdraw, | |
uint256 newMinTimeToWithdraw | |
); | |
event earned(uint256 oldWantLockedTotal, uint256 newWantLockedTotal); | |
constructor( | |
address[] memory _addresses, | |
uint256 _minTimeToWithdraw | |
) public { | |
govAddress = _addresses[0]; | |
KNABRFarmAddress = _addresses[1]; | |
LPaddress = _addresses[2]; | |
wantAddress = _addresses[3]; | |
minTimeToWithdraw = _minTimeToWithdraw; | |
transferOwnership(KNABRFarmAddress); | |
} | |
function deposit(address _userAddress, uint256 _wantAmt) | |
public | |
onlyOwner | |
nonReentrant | |
whenNotPaused | |
returns (uint256) | |
{ | |
if (userLastDepositedTimestamp[_userAddress] == 0) { | |
users.push(_userAddress); | |
} | |
userLastDepositedTimestamp[_userAddress] = block.timestamp; | |
IERC20(wantAddress).safeTransferFrom( | |
address(msg.sender), | |
address(this), | |
_wantAmt | |
); | |
uint256 sharesAdded = _wantAmt; | |
sharesTotal = sharesTotal.add(sharesAdded); | |
wantLockedTotal = IERC20(LPaddress).balanceOf(address(this)); | |
return sharesAdded; | |
} | |
function withdraw(address _userAddress, uint256 _wantAmt) | |
public | |
onlyOwner | |
nonReentrant | |
returns (uint256) | |
{ | |
require( | |
(userLastDepositedTimestamp[_userAddress].add(minTimeToWithdraw)) < | |
block.timestamp, | |
"too early!" | |
); | |
require(_wantAmt > 0, "_wantAmt <= 0"); | |
uint256 sharesRemoved = _wantAmt.mul(sharesTotal).div(wantLockedTotal); | |
if (sharesRemoved > sharesTotal) { | |
sharesRemoved = sharesTotal; | |
} | |
sharesTotal = sharesTotal.sub(sharesRemoved); | |
uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); | |
if (_wantAmt > wantAmt) { | |
_wantAmt = wantAmt; | |
} | |
if (wantLockedTotal < _wantAmt) { | |
_wantAmt = wantLockedTotal; | |
} | |
wantLockedTotal = wantLockedTotal.sub(_wantAmt); | |
IERC20(wantAddress).safeTransfer(KNABRFarmAddress, _wantAmt); | |
return sharesRemoved; | |
} | |
function _farm() internal {} | |
function _unfarm(uint256 _wantAmt) internal {} | |
function earn() public nonReentrant whenNotPaused { | |
if (onlyGov1) { | |
require(msg.sender == govAddress, "!gov"); | |
} | |
} | |
function setMinTimeToWithdraw(uint256 newMinTimeToWithdraw) | |
public | |
onlyAllowGov | |
{ | |
require(newMinTimeToWithdraw <= minTimeToWithdrawUL, "too high"); | |
emit minTimeToWithdrawChanged(minTimeToWithdraw, newMinTimeToWithdraw); | |
minTimeToWithdraw = newMinTimeToWithdraw; | |
} | |
function userLength() public view returns (uint256) { | |
return users.length; | |
} | |
receive() external payable {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity ^0.6.12; | |
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); | |
function decimals() external view returns (uint8); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) | |
external | |
returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) | |
external | |
view | |
returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval( | |
address indexed owner, | |
address indexed spender, | |
uint256 value | |
); | |
} | |
library SafeMath { | |
/** | |
* @dev Returns the addition of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `+` operator. | |
* | |
* Requirements: | |
* | |
* - Addition cannot overflow. | |
*/ | |
function add(uint256 a, uint256 b) internal pure returns (uint256) { | |
uint256 c = a + b; | |
require(c >= a, "SafeMath: addition overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub(uint256 a, uint256 b) internal pure returns (uint256) { | |
return sub(a, b, "SafeMath: subtraction overflow"); | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b <= a, errorMessage); | |
uint256 c = a - b; | |
return c; | |
} | |
/** | |
* @dev Returns the multiplication of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `*` operator. | |
* | |
* Requirements: | |
* | |
* - Multiplication cannot overflow. | |
*/ | |
function mul(uint256 a, uint256 b) internal pure returns (uint256) { | |
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the | |
// benefit is lost if 'b' is also tested. | |
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | |
if (a == 0) { | |
return 0; | |
} | |
uint256 c = a * b; | |
require(c / a == b, "SafeMath: multiplication overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div(uint256 a, uint256 b) internal pure returns (uint256) { | |
return div(a, b, "SafeMath: division by zero"); | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b > 0, errorMessage); | |
uint256 c = a / b; | |
// assert(a == b * c + a % b); // There is no case in which this doesn't hold | |
return c; | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod(uint256 a, uint256 b) internal pure returns (uint256) { | |
return mod(a, b, "SafeMath: modulo by zero"); | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts with custom message when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b != 0, errorMessage); | |
return a % b; | |
} | |
} | |
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; | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) | |
private | |
view | |
returns (bool) | |
{ | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) | |
private | |
view | |
returns (bytes32) | |
{ | |
require( | |
set._values.length > index, | |
"EnumerableSet: index out of bounds" | |
); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) | |
internal | |
view | |
returns (bytes32) | |
{ | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) | |
internal | |
view | |
returns (address) | |
{ | |
return address(uint256(_at(set._inner, index))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) | |
internal | |
view | |
returns (uint256) | |
{ | |
return uint256(_at(set._inner, index)); | |
} | |
} | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred( | |
address indexed previousOwner, | |
address indexed newOwner | |
); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() internal { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(_owner == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = address(0); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require( | |
newOwner != address(0), | |
"Ownable: new owner is the zero address" | |
); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
contract Pausable is Context { | |
/** | |
* @dev Emitted when the pause is triggered by `account`. | |
*/ | |
event Paused(address account); | |
/** | |
* @dev Emitted when the pause is lifted by `account`. | |
*/ | |
event Unpaused(address account); | |
bool private _paused; | |
/** | |
* @dev Initializes the contract in unpaused state. | |
*/ | |
constructor() internal { | |
_paused = false; | |
} | |
/** | |
* @dev Returns true if the contract is paused, and false otherwise. | |
*/ | |
function paused() public view returns (bool) { | |
return _paused; | |
} | |
/** | |
* @dev Modifier to make a function callable only when the contract is not paused. | |
* | |
* 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()); | |
} | |
} | |
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" | |
); | |
} | |
} | |
} | |
abstract contract StratX2 is Ownable, ReentrancyGuard, Pausable { | |
using SafeMath for uint256; | |
using SafeERC20 for IERC20; | |
address public KNABRFarmAddress; | |
address public govAddress; // timelock contract | |
// uint256 public lastEarnBlock = 0; | |
uint256 public wantLockedTotal = 0; | |
uint256 public sharesTotal = 0; | |
event SetGov(address _govAddress); | |
modifier onlyAllowGov() { | |
require(msg.sender == govAddress, "!gov"); | |
_; | |
} | |
function pause() public virtual onlyAllowGov { | |
_pause(); | |
} | |
function unpause() public virtual onlyAllowGov { | |
_unpause(); | |
} | |
function setGov(address _govAddress) public virtual onlyAllowGov { | |
govAddress = _govAddress; | |
emit SetGov(_govAddress); | |
} | |
} | |
interface aavePool { | |
function get_virtual_price() external returns (uint256); | |
function calc_token_amount(uint256[3] memory, bool) | |
external | |
returns (uint256); | |
function add_liquidity( | |
uint256[3] memory, | |
uint256, | |
bool | |
) external returns (uint256); | |
function remove_liquidity( | |
uint256, | |
uint256[3] memory, | |
bool | |
) external returns (uint256[3] memory); | |
function remove_liquidity_imbalance( | |
uint256[3] memory, | |
uint256, | |
bool | |
) external returns (uint256); | |
} | |
interface aaveGauge { | |
function deposit(uint256) external; | |
function withdraw(uint256) external; | |
function balanceOf(address) external returns (uint256); | |
function claim_rewards() external; | |
function claim_historic_rewards(address[8] memory) external; | |
} | |
interface DFYN { | |
function swapExactTokensForTokens( | |
uint256, | |
uint256, | |
address[] calldata, | |
address, | |
uint256 | |
) external; | |
} | |
interface SushiSwap { | |
function swapExactTokensForTokens( | |
uint256, | |
uint256, | |
address[] calldata, | |
address, | |
uint256 | |
) external; | |
} | |
contract AaveStrategy is StratX2 { | |
using SafeERC20 for IERC20; | |
using SafeMath for uint256; | |
address[] public users; | |
mapping(address => uint256) public userLastDepositedTimestamp; | |
uint256 public constant N_COINS = 3; | |
IERC20[N_COINS] public tokens; | |
IERC20 public poolToken; | |
IERC20 public WMatic; | |
aavePool public pool; | |
aaveGauge public gauge; | |
DFYN public dfyn; | |
address public weth; | |
address public dev; | |
IERC20 public crv; | |
SushiSwap public sushiSwap; | |
uint256 public constant DENOMINATOR = 10000; | |
uint256 public depositSlip = 100; | |
uint256 public withdrawSlip = 100; | |
address public loanWallet; | |
uint256 public loanpercent = 3000; | |
uint256 minTimeToWithdraw; | |
uint256 minTimeToWithdrawLoan; | |
uint256 public minTimeToWithdrawUL = 1209600; // 2 weeks | |
uint256 public minTimeToWithdrawLoanUL = 1209600; // 2 weeks | |
mapping(address => uint256) public amountLoan; | |
mapping(address => uint256) public paymentrecieved; | |
// mapping (address =>AmountReturn) public returnDetails; | |
// struct AmountReturn{ | |
// uint amount; | |
// uint time; | |
// } | |
event minTimeToWithdrawChanged( | |
uint256 oldMinTimeToWithdraw, | |
uint256 newMinTimeToWithdraw, | |
uint256 oldMinTimeToWithdraw2, | |
uint256 newMinTimeToWithdraw2 | |
); | |
event loanPercentChanged( | |
uint256 loanpercent | |
); | |
modifier onlyAuthorized() { | |
require( | |
govAddress == msg.sender || msg.sender == KNABRFarmAddress, | |
"Not authorized" | |
); | |
_; | |
} | |
modifier onlyGov() { | |
require((govAddress == msg.sender), "Not Authorized"); | |
_; | |
} | |
modifier onlyFarm() { | |
require(msg.sender == KNABRFarmAddress, "Not authorized"); | |
_; | |
} | |
constructor( | |
address _onlyGov, | |
address _tokens, | |
address _knabfarmaddress, | |
address _pool, | |
address _poolToken, | |
address _wmatic, | |
address _gauge, | |
address _dfyn, | |
address _weth, | |
address _dev, | |
address _crv, | |
address _ss, | |
uint256 _minTimeToWithdraw, | |
uint256 _minTimeToWithdrawLoan | |
) public { | |
govAddress = _onlyGov; | |
tokens[0] = IERC20(_tokens); | |
KNABRFarmAddress = _knabfarmaddress; | |
pool = aavePool(_pool); | |
poolToken = IERC20(_poolToken); | |
WMatic = IERC20(_wmatic); | |
gauge = aaveGauge(_gauge); | |
dfyn = DFYN(_dfyn); | |
weth = _weth; | |
minTimeToWithdraw = _minTimeToWithdraw; | |
minTimeToWithdrawLoan = _minTimeToWithdrawLoan; | |
crv = IERC20(_crv); | |
dev = _dev; | |
sushiSwap = SushiSwap(_ss); | |
transferOwnership(KNABRFarmAddress); | |
} | |
function newLoanWallet(address _wallet) external onlyGov { | |
loanWallet = _wallet; | |
} | |
function changeLoanNum(uint256 num) external onlyGov { | |
loanpercent = num; | |
emit loanPercentChanged(num.div(10000)); | |
} | |
function changeDepositSlip(uint256 _value) external onlyGov() { | |
depositSlip = _value; | |
} | |
// deposits stable tokens into the aave pool and stake recived LPtoken in the curve aave pool gauge | |
function deposit(address _userAddress, uint256 amount) | |
public | |
nonReentrant | |
whenNotPaused | |
onlyFarm() | |
returns (uint256) | |
{ | |
if (userLastDepositedTimestamp[_userAddress] == 0) { | |
users.push(_userAddress); | |
} | |
tokens[0].safeTransferFrom( | |
address(msg.sender), | |
address(this), | |
amount | |
); | |
userLastDepositedTimestamp[_userAddress] = block.timestamp; | |
deposit2(_userAddress, amount.mul(loanpercent).div(10000)); | |
amount = amount - amount.mul(loanpercent).div(10000); | |
uint256 sharesAdded = amount; | |
sharesTotal = sharesTotal.add(sharesAdded); | |
farm(amount); | |
return sharesAdded; | |
} | |
function deposit2(address user, uint256 amount) internal { | |
if (amount > 0) { | |
tokens[0].safeTransfer(loanWallet, amount); | |
amountLoan[user] += amount; | |
} | |
} | |
function withdraw2(address _user, uint amount) public nonReentrant onlyFarm() { | |
require( | |
((userLastDepositedTimestamp[_user].add(minTimeToWithdrawLoan)) < | |
block.timestamp) || paymentrecieved[_user]>0, | |
"too early!" | |
); | |
require(amount <= paymentrecieved[_user],'Amount exceeded'); | |
require( | |
tokens[0].balanceOf(address(this)) >= amount, | |
"Insufficient funds in contract... Contact owner" | |
); | |
tokens[0].safeTransfer(_user, amount); | |
paymentrecieved[_user] -= amount; | |
} | |
function withdrawloanall(address _user) public onlyFarm(){ | |
withdraw2(_user, paymentrecieved[_user]); | |
} | |
function updateLoan(address _user) public returns(uint){ | |
amountLoan[_user]=amountLoan[_user].add( | |
amountLoan[_user].mul((block.timestamp.sub(userLastDepositedTimestamp[_user])).div(2628000)).div(1200)); | |
return amountLoan[_user]; | |
} | |
function payback(address _user) public { | |
require(amountLoan[_user]>0,'No debt left'); | |
updateLoan(_user); | |
tokens[0].safeTransferFrom(msg.sender, address(this), amountLoan[_user]); | |
paymentrecieved[_user] += amountLoan[_user]; | |
amountLoan[_user] = 0; | |
} | |
//withdraws stable tokens from the aave pool.Unstake required LPtokens and stake LP tokens if not used. | |
function withdraw(address _userAddress, | |
uint256 amount | |
,uint256 bamount | |
) | |
public | |
nonReentrant | |
whenNotPaused | |
onlyFarm() | |
returns (uint256) | |
{ | |
require( | |
(userLastDepositedTimestamp[_userAddress].add(minTimeToWithdraw)) < | |
block.timestamp, | |
"too early!" | |
); | |
uint256[N_COINS] memory amounts = [amount, 0, 0]; | |
_unfarm(bamount); | |
pool.remove_liquidity_imbalance(amounts, | |
bamount | |
, true); | |
uint256 sharesRemoved = amount.div(wantLockedTotal).mul(sharesTotal); | |
sharesTotal = sharesTotal.sub(sharesRemoved); | |
if (amounts[0] != 0) { | |
tokens[0].safeTransfer(KNABRFarmAddress, amount); | |
} | |
if (poolToken.balanceOf(address(this)) > 0) { | |
_farm(); | |
} | |
wantLockedTotal = wantLockedTotal.sub(amount); | |
return sharesRemoved; | |
} | |
//unstake all the LPtokens and withdraw all the Stable tokens from aave pool | |
// function withdrawAll() | |
// external | |
// onlyFarm() | |
// returns (uint256[N_COINS] memory) | |
// { | |
// _unfarm(gauge.balanceOf(address(this))); | |
// uint256[N_COINS] memory withdrawAmt; | |
// pool.remove_liquidity( | |
// poolToken.balanceOf(address(this)), | |
// withdrawAmt, | |
// true | |
// ); | |
// for (uint8 i = 0; i < N_COINS; i++) { | |
// if (tokens[i].balanceOf(address(this)) != 0) { | |
// withdrawAmt[i] = tokens[i].balanceOf(address(this)); | |
// tokens[i].safeTransfer(KNABRFarmAddress, withdrawAmt[i]); | |
// } | |
// } | |
// return withdrawAmt; | |
// } | |
function farm(uint256 amount) internal { | |
uint256 decimal; | |
decimal = tokens[0].decimals(); | |
tokens[0].safeApprove(address(pool), 0); | |
tokens[0].safeApprove(address(pool), amount); | |
wantLockedTotal = wantLockedTotal.add(amount); | |
uint256[3] memory amounts = [amount, 0, 0]; | |
amount = amount.mul(1e18).div(10**decimal); | |
uint256 mintAmount = amount.mul(1e18).div(pool.get_virtual_price()); | |
pool.add_liquidity( | |
amounts, | |
mintAmount.mul(DENOMINATOR.sub(depositSlip)).div(DENOMINATOR), | |
true | |
); | |
_farm(); | |
} | |
function _farm() internal { | |
uint256 depositAmt = poolToken.balanceOf(address(this)); | |
poolToken.safeApprove(address(gauge), 0); | |
poolToken.safeApprove(address(gauge), depositAmt); | |
gauge.deposit(depositAmt); | |
emit staked(depositAmt); | |
} | |
//For unstaking LP tokens | |
function _unfarm(uint256 _amount) internal { | |
require( | |
gauge.balanceOf(address(this)) >= _amount, | |
"You have not staked that much amount" | |
); | |
gauge.withdraw(_amount); | |
emit unstaked(_amount); | |
} | |
function earn() external nonReentrant whenNotPaused onlyGov() { | |
claimWMatic(); | |
uint256 amountsub = tokens[0].balanceOf(address(this)); | |
swapWMatic(WMatic.balanceOf(address(this)), 0); | |
swapCRV(crv.balanceOf(address(this)), 0); | |
uint256 amount = tokens[0].balanceOf(address(this)).sub(amountsub); | |
if (amount > 0) { | |
farm(amount); | |
} | |
} | |
//function for claiming wmatic rewards | |
function claimWMatic() internal { | |
gauge.claim_rewards(); | |
} | |
//function for claiming historic rewards | |
function claimHistoricReward(address[8] memory _rewardTokens) | |
external | |
onlyGov() | |
{ | |
gauge.claim_historic_rewards(_rewardTokens); | |
} | |
function swapWMatic(uint256 _amount, uint256 _minimumAmount) internal { | |
require( | |
WMatic.balanceOf(address(this)) >= _amount, | |
"Insufficient WMatic amount" | |
); | |
WMatic.safeApprove(address(dfyn), 0); | |
WMatic.safeApprove(address(dfyn), _amount); | |
address[] memory path; | |
path = new address[](3); | |
path[0] = address(WMatic); | |
path[1] = weth; | |
path[2] = address(tokens[0]); | |
dfyn.swapExactTokensForTokens( | |
_amount, | |
_minimumAmount, | |
path, | |
address(this), | |
now + 600 | |
); | |
} | |
function swapCRV(uint256 _amount, uint256 _minimumAmount) internal { | |
require( | |
crv.balanceOf(address(this)) >= _amount, | |
"Insufficient CRV amount" | |
); | |
crv.safeApprove(address(sushiSwap), 0); | |
crv.safeApprove(address(sushiSwap), _amount); | |
address[] memory path; | |
path = new address[](3); | |
path[0] = address(crv); | |
path[1] = weth; | |
path[2] = address(tokens[0]); | |
sushiSwap.swapExactTokensForTokens( | |
_amount, | |
_minimumAmount, | |
path, | |
address(this), | |
now + 600 | |
); | |
} | |
// Added to support recovering tokens | |
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) | |
external | |
onlyGov() | |
{ | |
require( | |
_tokenAddress != address(poolToken), | |
"Cannot withdraw LP token" | |
); | |
IERC20(_tokenAddress).safeTransfer(address(dev), _tokenAmount); | |
emit Recovered(_tokenAddress, _tokenAmount); | |
} | |
function setMinTimeToWithdraw2(uint256 withdrawal1, uint256 withdrawal2) | |
public | |
onlyAllowGov | |
{ | |
require(withdrawal1 <= minTimeToWithdrawUL, "too high"); | |
require(withdrawal2 <= minTimeToWithdrawLoanUL, "too high"); | |
emit minTimeToWithdrawChanged( | |
minTimeToWithdraw, | |
withdrawal1, | |
minTimeToWithdrawLoan, | |
withdrawal2 | |
); | |
minTimeToWithdraw = withdrawal1; | |
minTimeToWithdrawLoan = withdrawal2; | |
} | |
event unstaked(uint256 amount); | |
event staked(uint256 amount); | |
event onlyGovNominated(address newOwner); | |
event onlyGovChanged(address oldOwner, address newOwner); | |
event Recovered(address, uint256); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.6.12; | |
pragma solidity >=0.6.9 <0.8.0; | |
pragma experimental ABIEncoderV2; | |
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; | |
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 | |
); | |
} | |
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; | |
} | |
} | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) | |
private | |
view | |
returns (bool) | |
{ | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) | |
private | |
view | |
returns (bytes32) | |
{ | |
require( | |
set._values.length > index, | |
"EnumerableSet: index out of bounds" | |
); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) | |
internal | |
view | |
returns (bytes32) | |
{ | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _add(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(uint256(value))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) | |
internal | |
view | |
returns (address) | |
{ | |
return address(uint256(_at(set._inner, index))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) | |
internal | |
returns (bool) | |
{ | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) | |
internal | |
view | |
returns (bool) | |
{ | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) | |
internal | |
view | |
returns (uint256) | |
{ | |
return uint256(_at(set._inner, index)); | |
} | |
} | |
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.3._ | |
*/ | |
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.3._ | |
*/ | |
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); | |
} | |
} | |
} | |
} | |
abstract contract AccessControl is Context { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
using Address for address; | |
struct RoleData { | |
EnumerableSet.AddressSet members; | |
bytes32 adminRole; | |
} | |
mapping(bytes32 => RoleData) private _roles; | |
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; | |
/** | |
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` | |
* | |
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite | |
* {RoleAdminChanged} not being emitted signaling this. | |
* | |
* _Available since v3.1._ | |
*/ | |
event RoleAdminChanged( | |
bytes32 indexed role, | |
bytes32 indexed previousAdminRole, | |
bytes32 indexed newAdminRole | |
); | |
/** | |
* @dev Emitted when `account` is granted `role`. | |
* | |
* `sender` is the account that originated the contract call, an admin role | |
* bearer except when using {_setupRole}. | |
*/ | |
event RoleGranted( | |
bytes32 indexed role, | |
address indexed account, | |
address indexed sender | |
); | |
/** | |
* @dev Emitted when `account` is revoked `role`. | |
* | |
* `sender` is the account that originated the contract call: | |
* - if using `revokeRole`, it is the admin role bearer | |
* - if using `renounceRole`, it is the role bearer (i.e. `account`) | |
*/ | |
event RoleRevoked( | |
bytes32 indexed role, | |
address indexed account, | |
address indexed sender | |
); | |
/** | |
* @dev Returns `true` if `account` has been granted `role`. | |
*/ | |
function hasRole(bytes32 role, address account) public view returns (bool) { | |
return _roles[role].members.contains(account); | |
} | |
/** | |
* @dev Returns the number of accounts that have `role`. Can be used | |
* together with {getRoleMember} to enumerate all bearers of a role. | |
*/ | |
function getRoleMemberCount(bytes32 role) public view returns (uint256) { | |
return _roles[role].members.length(); | |
} | |
/** | |
* @dev Returns one of the accounts that have `role`. `index` must be a | |
* value between 0 and {getRoleMemberCount}, non-inclusive. | |
* | |
* Role bearers are not sorted in any particular way, and their ordering may | |
* change at any point. | |
* | |
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure | |
* you perform all queries on the same block. See the following | |
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] | |
* for more information. | |
*/ | |
function getRoleMember(bytes32 role, uint256 index) | |
public | |
view | |
returns (address) | |
{ | |
return _roles[role].members.at(index); | |
} | |
/** | |
* @dev Returns the admin role that controls `role`. See {grantRole} and | |
* {revokeRole}. | |
* | |
* To change a role's admin, use {_setRoleAdmin}. | |
*/ | |
function getRoleAdmin(bytes32 role) public view returns (bytes32) { | |
return _roles[role].adminRole; | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function grantRole(bytes32 role, address account) public virtual { | |
require( | |
hasRole(_roles[role].adminRole, _msgSender()), | |
"AccessControl: sender must be an admin to grant" | |
); | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* If `account` had been granted `role`, emits a {RoleRevoked} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function revokeRole(bytes32 role, address account) public virtual { | |
require( | |
hasRole(_roles[role].adminRole, _msgSender()), | |
"AccessControl: sender must be an admin to revoke" | |
); | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from the calling account. | |
* | |
* Roles are often managed via {grantRole} and {revokeRole}: this function's | |
* purpose is to provide a mechanism for accounts to lose their privileges | |
* if they are compromised (such as when a trusted device is misplaced). | |
* | |
* If the calling account had been granted `role`, emits a {RoleRevoked} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must be `account`. | |
*/ | |
function renounceRole(bytes32 role, address account) public virtual { | |
require( | |
account == _msgSender(), | |
"AccessControl: can only renounce roles for self" | |
); | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. Note that unlike {grantRole}, this function doesn't perform any | |
* checks on the calling account. | |
* | |
* [WARNING] | |
* ==== | |
* This function should only be called from the constructor when setting | |
* up the initial roles for the system. | |
* | |
* Using this function in any other way is effectively circumventing the admin | |
* system imposed by {AccessControl}. | |
* ==== | |
*/ | |
function _setupRole(bytes32 role, address account) internal virtual { | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Sets `adminRole` as ``role``'s admin role. | |
* | |
* Emits a {RoleAdminChanged} event. | |
*/ | |
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { | |
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); | |
_roles[role].adminRole = adminRole; | |
} | |
function _grantRole(bytes32 role, address account) private { | |
if (_roles[role].members.add(account)) { | |
emit RoleGranted(role, account, _msgSender()); | |
} | |
} | |
function _revokeRole(bytes32 role, address account) private { | |
if (_roles[role].members.remove(account)) { | |
emit RoleRevoked(role, account, _msgSender()); | |
} | |
} | |
} | |
abstract contract ReentrancyGuard { | |
// Booleans are more expensive than uint256 or any type that takes up a full | |
// word because each write operation emits an extra SLOAD to first read the | |
// slot's contents, replace the bits taken up by the boolean, and then write | |
// back. This is the compiler's defense against contract upgrades and | |
// pointer aliasing, and it cannot be disabled. | |
// The values being non-zero value makes deployment a bit more expensive, | |
// but in exchange the refund on every call to nonReentrant will be lower in | |
// amount. Since refunds are capped to a percentage of the total | |
// transaction's gas, it is best to keep them low in cases like this one, to | |
// increase the likelihood of the full refund coming into effect. | |
uint256 private constant _NOT_ENTERED = 1; | |
uint256 private constant _ENTERED = 2; | |
uint256 private _status; | |
constructor() internal { | |
_status = _NOT_ENTERED; | |
} | |
/** | |
* @dev Prevents a contract from calling itself, directly or indirectly. | |
* Calling a `nonReentrant` function from another `nonReentrant` | |
* function is not supported. It is possible to prevent this from happening | |
* by making the `nonReentrant` function external, and make it call a | |
* `private` function that does the actual work. | |
*/ | |
modifier nonReentrant() { | |
// On the first call to nonReentrant, _notEntered will be true | |
require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); | |
// Any calls to nonReentrant after this point will fail | |
_status = _ENTERED; | |
_; | |
// By storing the original value once again, a refund is triggered (see | |
// https://eips.ethereum.org/EIPS/eip-2200) | |
_status = _NOT_ENTERED; | |
} | |
} | |
library SafeMath { | |
/** | |
* @dev Returns the addition of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `+` operator. | |
* | |
* Requirements: | |
* | |
* - Addition cannot overflow. | |
*/ | |
function add(uint256 a, uint256 b) internal pure returns (uint256) { | |
uint256 c = a + b; | |
require(c >= a, "SafeMath: addition overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub(uint256 a, uint256 b) internal pure returns (uint256) { | |
return sub(a, b, "SafeMath: subtraction overflow"); | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b <= a, errorMessage); | |
uint256 c = a - b; | |
return c; | |
} | |
/** | |
* @dev Returns the multiplication of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `*` operator. | |
* | |
* Requirements: | |
* | |
* - Multiplication cannot overflow. | |
*/ | |
function mul(uint256 a, uint256 b) internal pure returns (uint256) { | |
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the | |
// benefit is lost if 'b' is also tested. | |
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | |
if (a == 0) { | |
return 0; | |
} | |
uint256 c = a * b; | |
require(c / a == b, "SafeMath: multiplication overflow"); | |
return c; | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div(uint256 a, uint256 b) internal pure returns (uint256) { | |
return div(a, b, "SafeMath: division by zero"); | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b > 0, errorMessage); | |
uint256 c = a / b; | |
// assert(a == b * c + a % b); // There is no case in which this doesn't hold | |
return c; | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod(uint256 a, uint256 b) internal pure returns (uint256) { | |
return mod(a, b, "SafeMath: modulo by zero"); | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts with custom message when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b != 0, errorMessage); | |
return a % b; | |
} | |
} | |
/** | |
* @dev Farm functions that do not require less than the min timelock | |
*/ | |
interface IKNABRFarm { | |
function add( | |
uint256 _allocPoint, | |
address _want, | |
bool _withUpdate, | |
address _strat | |
) external; | |
function set( | |
uint256 _pid, | |
uint256 _allocPoint, | |
bool _withUpdate | |
) external; | |
function inCaseTokensGetStuck(address _token, uint256 _amount) external; | |
} | |
/** | |
* @dev Strategy functions that do not require timelock or have a timelock less than the min timelock | |
*/ | |
interface IStrategy { | |
function earn() external; | |
function farm() external; | |
function pause() external; | |
function unpause() external; | |
function rebalance(uint256 _borrowRate, uint256 _borrowDepth) external; | |
function recoverERC20(address _token, uint _amt) external; | |
function setMinTimeToWithdraw(uint newmintime) external; | |
function changeDepositSlipCurve() external; | |
function newLoanWallet(address _wallet) external; | |
function setMinTimeToWithdraw2(uint withdrawtime1,uint withdrawtime2) external; | |
}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" | |
); | |
} | |
} | |
} | |
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/TimelockController.sol"; | |
/** | |
* @dev Contract module which acts as a timelocked controller. When set as the | |
* owner of an `Ownable` smart contract, it enforces a timelock on all | |
* `onlyOwner` maintenance operations. This gives time for users of the | |
* controlled contract to exit before a potentially dangerous maintenance | |
* operation is applied. | |
* | |
* By default, this contract is self administered, meaning administration tasks | |
* have to go through the timelock process. The proposer (resp executor) role | |
* is in charge of proposing (resp executing) operations. A common use case is | |
* to position this {TimelockController} as the owner of a smart contract, with | |
* a multisig or a DAO as the sole proposer. | |
* | |
* _Available since v3.3._ | |
*/ | |
contract TimelockController is AccessControl, ReentrancyGuard { | |
using SafeERC20 for IERC20; | |
bytes32 public constant TIMELOCK_ADMIN_ROLE = | |
keccak256("TIMELOCK_ADMIN_ROLE"); | |
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); | |
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); | |
uint256 internal constant _DONE_TIMESTAMP = uint256(1); | |
mapping(bytes32 => uint256) private _timestamps; | |
uint256 public minDelay; // seconds - to be increased in production | |
uint256 public minDelayReduced; // seconds - to be increased in production | |
address payable public devWalletAddress; | |
/** | |
* @dev Emitted when a call is scheduled as part of operation `id`. | |
*/ | |
event CallScheduled( | |
bytes32 indexed id, | |
uint256 indexed index, | |
address target, | |
uint256 value, | |
bytes data, | |
bytes32 predecessor, | |
uint256 delay | |
); | |
/** | |
* @dev Emitted when a call is scheduled as part of operation `id`. | |
*/ | |
event SetScheduled( | |
bytes32 indexed id, | |
uint256 indexed index, | |
uint256 _pid, | |
uint256 _allocPoint, | |
bool _withUpdate, | |
bytes32 predecessor, | |
uint256 delay | |
); | |
event EarnScheduled( | |
bytes32 indexed id, | |
uint256 indexed index, | |
bytes32 predecessor, | |
uint256 delay | |
); | |
/** | |
* @dev Emitted when a call is performed as part of operation `id`. | |
*/ | |
event CallExecuted( | |
bytes32 indexed id, | |
uint256 indexed index, | |
address target, | |
uint256 value, | |
bytes data | |
); | |
/** | |
* @dev Emitted when operation `id` is cancelled. | |
*/ | |
event Cancelled(bytes32 indexed id); | |
/** | |
* @dev Emitted when the minimum delay for future operations is modified. | |
*/ | |
event MinDelayChange(uint256 oldDuration, uint256 newDuration); | |
event MinDelayReducedChange(uint256 oldDuration, uint256 newDuration); | |
event SetScheduled( | |
bytes32 indexed id, | |
uint256 indexed index, | |
address target, | |
uint256 value, | |
bytes data, | |
bytes32 predecessor, | |
uint256 delay | |
); | |
/** | |
* @dev Initializes the contract with a given `minDelay`. | |
*/ | |
constructor( | |
address payable _devWalletAddress, | |
uint256 _minDelay, | |
uint256 _minDelayReduced // address[] memory proposers, address[] memory executors | |
) public { | |
devWalletAddress = _devWalletAddress; | |
minDelay = _minDelay; | |
minDelayReduced = _minDelayReduced; | |
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); | |
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); | |
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); | |
// deployer + self administration | |
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); | |
_setupRole(TIMELOCK_ADMIN_ROLE, address(this)); | |
// register proposers | |
// for (uint256 i = 0; i < proposers.length; ++i) { | |
// _setupRole(PROPOSER_ROLE, proposers[i]); | |
// } | |
_setupRole(PROPOSER_ROLE, devWalletAddress); | |
// // register executors | |
// for (uint256 i = 0; i < executors.length; ++i) { | |
// _setupRole(EXECUTOR_ROLE, executors[i]); | |
// } | |
_setupRole(EXECUTOR_ROLE, devWalletAddress); | |
emit MinDelayChange(0, minDelay); | |
} | |
/** | |
* @dev Modifier to make a function callable only by a certain role. In | |
* addition to checking the sender's role, `address(0)` 's role is also | |
* considered. Granting a role to `address(0)` is equivalent to enabling | |
* this role for everyone. | |
*/ | |
modifier onlyRole(bytes32 role) { | |
require( | |
hasRole(role, _msgSender()) || hasRole(role, address(0)), | |
"TimelockController: sender requires permission" | |
); | |
_; | |
} | |
/** | |
* @dev Contract might receive/hold ETH as part of the maintenance process. | |
*/ | |
receive() external payable {} | |
/** | |
* @dev Returns whether an operation is pending or not. | |
*/ | |
function isOperationPending(bytes32 id) public view returns (bool pending) { | |
return _timestamps[id] > _DONE_TIMESTAMP; | |
} | |
/** | |
* @dev Returns whether an operation is ready or not. | |
*/ | |
function isOperationReady(bytes32 id) public view returns (bool ready) { | |
// solhint-disable-next-line not-rely-on-time | |
return | |
_timestamps[id] > _DONE_TIMESTAMP && | |
_timestamps[id] <= block.timestamp; | |
} | |
/** | |
* @dev Returns whether an operation is done or not. | |
*/ | |
function isOperationDone(bytes32 id) public view returns (bool done) { | |
return _timestamps[id] == _DONE_TIMESTAMP; | |
} | |
/** | |
* @dev Returns the timestamp at with an operation becomes ready (0 for | |
* unset operations, 1 for done operations). | |
*/ | |
function getTimestamp(bytes32 id) public view returns (uint256 timestamp) { | |
return _timestamps[id]; | |
} | |
/** | |
* @dev Returns the minimum delay for an operation to become valid. | |
* | |
* This value can be changed by executing an operation that calls `updateDelay`. | |
*/ | |
function getMinDelay() public view returns (uint256 duration) { | |
return minDelay; | |
} | |
/** | |
* @dev Returns the identifier of an operation containing a single | |
* transaction. | |
*/ | |
function hashOperation( | |
address target, | |
uint256 value, | |
bytes calldata data, | |
bytes32 predecessor, | |
bytes32 salt | |
) public pure returns (bytes32 hash) { | |
return keccak256(abi.encode(target, value, data, predecessor, salt)); | |
} | |
/** | |
* @dev Returns the identifier of an operation containing a batch of | |
* transactions. | |
*/ | |
function hashOperationBatch( | |
address[] calldata targets, | |
uint256[] calldata values, | |
bytes[] calldata datas, | |
bytes32 predecessor, | |
bytes32 salt | |
) public pure returns (bytes32 hash) { | |
return keccak256(abi.encode(targets, values, datas, predecessor, salt)); | |
} | |
/** | |
* @dev Schedule an operation containing a single transaction. | |
* | |
* Emits a {CallScheduled} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have the 'proposer' role. | |
*/ | |
function schedule( | |
address target, | |
uint256 value, | |
bytes calldata data, | |
bytes32 predecessor, | |
bytes32 salt, | |
uint256 delay | |
) public virtual onlyRole(PROPOSER_ROLE) { | |
bytes32 id = hashOperation(target, value, data, predecessor, salt); | |
_schedule(id, delay); | |
emit CallScheduled(id, 0, target, value, data, predecessor, delay); | |
} | |
/** | |
* @dev Schedule an operation containing a batch of transactions. | |
* | |
* Emits one {CallScheduled} event per transaction in the batch. | |
* | |
* Requirements: | |
* | |
* - the caller must have the 'proposer' role. | |
*/ | |
function scheduleBatch( | |
address[] calldata targets, | |
uint256[] calldata values, | |
bytes[] calldata datas, | |
bytes32 predecessor, | |
bytes32 salt, | |
uint256 delay | |
) public virtual onlyRole(PROPOSER_ROLE) { | |
require( | |
targets.length == values.length, | |
"TimelockController: length mismatch" | |
); | |
require( | |
targets.length == datas.length, | |
"TimelockController: length mismatch" | |
); | |
bytes32 id = | |
hashOperationBatch(targets, values, datas, predecessor, salt); | |
_schedule(id, delay); | |
for (uint256 i = 0; i < targets.length; ++i) { | |
emit CallScheduled( | |
id, | |
i, | |
targets[i], | |
values[i], | |
datas[i], | |
predecessor, | |
delay | |
); | |
} | |
} | |
/** | |
* @dev Schedule an operation that is to becomes valid after a given delay. | |
*/ | |
function _schedule(bytes32 id, uint256 delay) private { | |
require( | |
_timestamps[id] == 0, | |
"TimelockController: operation already scheduled" | |
); | |
require(delay >= minDelay, "TimelockController: insufficient delay"); | |
// solhint-disable-next-line not-rely-on-time | |
_timestamps[id] = SafeMath.add(block.timestamp, delay); | |
} | |
/** | |
* @dev Cancel an operation. | |
* | |
* Requirements: | |
* | |
* - the caller must have the 'proposer' role. | |
*/ | |
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { | |
require( | |
isOperationPending(id), | |
"TimelockController: operation cannot be cancelled" | |
); | |
delete _timestamps[id]; | |
emit Cancelled(id); | |
} | |
/** | |
* @dev Execute an (ready) operation containing a single transaction. | |
* | |
* Emits a {CallExecuted} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have the 'executor' role. | |
*/ | |
function execute( | |
address target, | |
uint256 value, | |
bytes calldata data, | |
bytes32 predecessor, | |
bytes32 salt | |
) public payable virtual onlyRole(EXECUTOR_ROLE) nonReentrant { | |
bytes32 id = hashOperation(target, value, data, predecessor, salt); | |
_beforeCall(predecessor); | |
_call(id, 0, target, value, data); | |
_afterCall(id); | |
} | |
/** | |
* @dev Execute an (ready) operation containing a batch of transactions. | |
* | |
* Emits one {CallExecuted} event per transaction in the batch. | |
* | |
* Requirements: | |
* | |
* - the caller must have the 'executor' role. | |
*/ | |
function executeBatch( | |
address[] calldata targets, | |
uint256[] calldata values, | |
bytes[] calldata datas, | |
bytes32 predecessor, | |
bytes32 salt | |
) public payable virtual onlyRole(EXECUTOR_ROLE) nonReentrant { | |
require( | |
targets.length == values.length, | |
"TimelockController: length mismatch" | |
); | |
require( | |
targets.length == datas.length, | |
"TimelockController: length mismatch" | |
); | |
bytes32 id = | |
hashOperationBatch(targets, values, datas, predecessor, salt); | |
_beforeCall(predecessor); | |
for (uint256 i = 0; i < targets.length; ++i) { | |
_call(id, i, targets[i], values[i], datas[i]); | |
} | |
_afterCall(id); | |
} | |
/** | |
* @dev Checks before execution of an operation's calls. | |
*/ | |
function _beforeCall(bytes32 predecessor) private view { | |
require( | |
predecessor == bytes32(0) || isOperationDone(predecessor), | |
"TimelockController: missing dependency" | |
); | |
} | |
/** | |
* @dev Checks after execution of an operation's calls. | |
*/ | |
function _afterCall(bytes32 id) private { | |
require( | |
isOperationReady(id), | |
"TimelockController: operation is not ready" | |
); | |
_timestamps[id] = _DONE_TIMESTAMP; | |
} | |
/** | |
* @dev Execute an operation's call. | |
* | |
* Emits a {CallExecuted} event. | |
*/ | |
function _call( | |
bytes32 id, | |
uint256 index, | |
address target, | |
uint256 value, | |
bytes calldata data | |
) private { | |
// solhint-disable-next-line avoid-low-level-calls | |
(bool success, ) = target.call{value: value}(data); | |
require(success, "TimelockController: underlying transaction reverted"); | |
emit CallExecuted(id, index, target, value, data); | |
} | |
/** | |
* @dev Changes the minimum timelock duration for future operations. | |
* | |
* Emits a {MinDelayChange} event. | |
* | |
* Requirements: | |
* | |
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing | |
* an operation where the timelock is the target and the data is the ABI-encoded call to this function. | |
*/ | |
function updateMinDelay(uint256 newDelay) external virtual { | |
require( | |
msg.sender == address(this), | |
"TimelockController: caller must be timelock" | |
); | |
emit MinDelayChange(minDelay, newDelay); | |
minDelay = newDelay; | |
} | |
function updateMinDelayReduced(uint256 newDelay) external virtual { | |
require( | |
msg.sender == address(this), | |
"TimelockController: caller must be timelock" | |
); | |
emit MinDelayReducedChange(minDelayReduced, newDelay); | |
minDelayReduced = newDelay; | |
} | |
function setDevWalletAddress(address payable _devWalletAddress) public { | |
require( | |
msg.sender == address(this), | |
"TimelockController: caller must be timelock" | |
); | |
require(tx.origin == devWalletAddress, "tx.origin != devWalletAddress"); | |
devWalletAddress = _devWalletAddress; | |
} | |
/** | |
* @dev Reduced timelock functions | |
*/ | |
function scheduleSet( | |
address _autofarmAddress, | |
uint256 _pid, | |
uint256 _allocPoint, | |
bool _withUpdate, | |
bytes32 predecessor, | |
bytes32 salt | |
) public onlyRole(EXECUTOR_ROLE) { | |
bytes32 id = | |
keccak256( | |
abi.encode( | |
_autofarmAddress, | |
_pid, | |
_allocPoint, | |
_withUpdate, | |
predecessor, | |
salt | |
) | |
); | |
require( | |
_timestamps[id] == 0, | |
"TimelockController: operation already scheduled" | |
); | |
_timestamps[id] = SafeMath.add(block.timestamp, minDelayReduced); | |
emit SetScheduled( | |
id, | |
0, | |
_pid, | |
_allocPoint, | |
_withUpdate, | |
predecessor, | |
minDelayReduced | |
); | |
} | |
function executeSet( | |
address _autofarmAddress, | |
uint256 _pid, | |
uint256 _allocPoint, | |
bool _withUpdate, | |
bytes32 predecessor, | |
bytes32 salt | |
) public payable virtual onlyRole(EXECUTOR_ROLE) nonReentrant { | |
bytes32 id = | |
keccak256( | |
abi.encode( | |
_autofarmAddress, | |
_pid, | |
_allocPoint, | |
_withUpdate, | |
predecessor, | |
salt | |
) | |
); | |
_beforeCall(predecessor); | |
IKNABRFarm(_autofarmAddress).set(_pid, _allocPoint, _withUpdate); | |
_afterCall(id); | |
} | |
function withdrawERC20(address _tokenAddress) public payable { | |
require(msg.sender == devWalletAddress, "!devWalletAddress"); | |
uint256 tokenBal = IERC20(_tokenAddress).balanceOf(address(this)); | |
IERC20(_tokenAddress).safeIncreaseAllowance(devWalletAddress, tokenBal); | |
IERC20(_tokenAddress).safeTransfer(devWalletAddress, tokenBal); | |
} | |
function add( | |
address _autofarmAddress, | |
address _want, | |
bool _withUpdate, | |
address _strat | |
) public onlyRole(EXECUTOR_ROLE) { | |
IKNABRFarm(_autofarmAddress).add(0, _want, _withUpdate, _strat); // allocPoint = 0. Schedule set (timelocked) to increase allocPoint. | |
} | |
// function scheduleEarn( | |
// address _stratAddress, | |
// bytes32 predecessor, | |
// bytes32 salt | |
// ) public onlyRole(EXECUTOR_ROLE) { | |
// bytes32 id = | |
// keccak256( | |
// abi.encode( | |
// _stratAddress, | |
// predecessor, | |
// salt | |
// ) | |
// ); | |
// require( | |
// _timestamps[id] == 0, | |
// "TimelockController: operation already scheduled" | |
// ); | |
// _timestamps[id] = SafeMath.add(block.timestamp, minDelayReduced); | |
// emit EarnScheduled( | |
// id, | |
// 0, | |
// predecessor, | |
// minDelayReduced | |
// ); | |
// } | |
// function executeEarn( | |
// address _autofarmAddress, | |
// uint256 _pid, | |
// uint256 _allocPoint, | |
// bool _withUpdate, | |
// bytes32 predecessor, | |
// bytes32 salt | |
// ) public payable virtual onlyRole(EXECUTOR_ROLE) nonReentrant { | |
// bytes32 id = | |
// keccak256( | |
// abi.encode( | |
// _autofarmAddress, | |
// _pid, | |
// _allocPoint, | |
// _withUpdate, | |
// predecessor, | |
// salt | |
// ) | |
// ); | |
// _beforeCall(predecessor); | |
// IKNABRFarm(_autofarmAddress).set(_pid, _allocPoint, _withUpdate); | |
// _afterCall(id); | |
// } | |
// function earn(address _stratAddress) public onlyRole(EXECUTOR_ROLE) { | |
// IStrategy(_stratAddress).earn(); | |
// } | |
// function pause(address _stratAddress) public onlyRole(EXECUTOR_ROLE) { | |
// IStrategy(_stratAddress).pause(); | |
// } | |
// function unpause(address _stratAddress) public onlyRole(EXECUTOR_ROLE) { | |
// IStrategy(_stratAddress).unpause(); | |
// } | |
// function setMinTimeToWithdraw(address _stratAddress, uint newmintime) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IStrategy(_stratAddress).setMinTimeToWithdraw(newmintime); | |
// } | |
// function changeDepositSlipCurve(address _stratAddress) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IStrategy(_stratAddress).changeDepositSlipCurve(); | |
// } | |
// function setMinTimeToWithdraw2(address _stratAddress,uint withdrawtime1,uint withdrawtime2) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IStrategy(_stratAddress).setMinTimeToWithdraw2(withdrawtime1,withdrawtime2); | |
// } | |
// function recoverERC20Strat(address _stratAddress,address _token,uint _amt) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IStrategy(_stratAddress).recoverERC20(_token,_amt); | |
// } | |
// function changeLoanWalletAddress(address _stratAddress,address loanWallet) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IStrategy(_stratAddress).newLoanWallet(loanWallet); | |
// } | |
// function recoverERC20Farm(address _KnabrfarmAddress,address _token,uint _amt) | |
// public | |
// onlyRole(EXECUTOR_ROLE) | |
// { | |
// IKNABRFarm(_KnabrfarmAddress).inCaseTokensGetStuck(_token,_amt); | |
// } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
contract tokenTracker { | |
mapping(string => uint)[] internal tokenTrack; | |
mapping(address => uint) internal aur; | |
uint public tokens; | |
address public gov; | |
constructor(address _gov){ | |
gov = _gov; | |
} | |
//modifiers | |
modifier onlyGov{ | |
require(msg.sender == gov,'Not Authorised'); | |
_; | |
} | |
modifier onlyAur{ | |
require(aur[msg.sender]==1,'Not Authorised'); | |
_; | |
} | |
//view functions | |
function totalSold (string memory refId)external view returns(uint[]memory){ | |
uint[] memory sold = new uint[](tokens); | |
for(uint i = 0;i<tokens;i++){ | |
sold[i]=(tokenSold(refId,i)); | |
} | |
return sold; | |
} | |
function tokenSold(string memory refId,uint index) public view returns(uint sold){ | |
return( | |
tokenTrack[index][refId] | |
); | |
} | |
// external func | |
function changeGov(address _newGov) external onlyGov{ | |
gov=_newGov; | |
} | |
function addToken() external onlyGov returns (uint){ | |
tokenTrack.push(); | |
tokens++; | |
return tokenTrack.length; | |
} | |
function addAur(address _aur) external onlyGov { | |
aur[_aur]=1; | |
} | |
function removeAur(address _aur) external onlyGov { | |
aur[_aur]=0; | |
} | |
function increase(uint index,string memory refId,uint amount) external onlyAur { | |
tokenTrack[index][refId]+=amount; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment