// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 16: BalanceManagement.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;import { ITokenBalance } from'./interfaces/ITokenBalance.sol';
import { ManagerRole } from'./roles/ManagerRole.sol';
import'./helpers/TransferHelper.sol'asTransferHelper;
import'./Constants.sol'asConstants;
/**
* @title BalanceManagement
* @notice Base contract for the withdrawal of tokens, except for reserved ones
*/abstractcontractBalanceManagementisManagerRole{
/**
* @notice Emitted when the specified token is reserved
*/errorReservedTokenError();
/**
* @notice Performs the withdrawal of tokens, except for reserved ones
* @dev Use the "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" address for the native token
* @param _tokenAddress The address of the token
* @param _tokenAmount The amount of the token
*/functioncleanup(address _tokenAddress, uint256 _tokenAmount) externalonlyManager{
if (isReservedToken(_tokenAddress)) {
revert ReservedTokenError();
}
if (_tokenAddress == Constants.NATIVE_TOKEN_ADDRESS) {
TransferHelper.safeTransferNative(msg.sender, _tokenAmount);
} else {
TransferHelper.safeTransfer(_tokenAddress, msg.sender, _tokenAmount);
}
}
/**
* @notice Getter of the token balance of the current contract
* @dev Use the "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" address for the native token
* @param _tokenAddress The address of the token
* @return The token balance of the current contract
*/functiontokenBalance(address _tokenAddress) publicviewreturns (uint256) {
if (_tokenAddress == Constants.NATIVE_TOKEN_ADDRESS) {
returnaddress(this).balance;
} else {
return ITokenBalance(_tokenAddress).balanceOf(address(this));
}
}
/**
* @notice Getter of the reserved token flag
* @dev Override to add reserved token addresses
* @param _tokenAddress The address of the token
* @return The reserved token flag
*/functionisReservedToken(address _tokenAddress) publicviewvirtualreturns (bool) {
// The function returns false by default.// The explicit return statement is omitted to avoid the unused parameter warning.// See https://github.com/ethereum/solidity/issues/5295
}
}
Contract Source Code
File 3 of 16: Constants.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;/**
* @dev The default token decimals value
*/uint256constant DECIMALS_DEFAULT =18;
/**
* @dev The maximum uint256 value for swap amount limit settings
*/uint256constant INFINITY =type(uint256).max;
/**
* @dev The default limit of account list size
*/uint256constant LIST_SIZE_LIMIT_DEFAULT =100;
/**
* @dev The limit of swap router list size
*/uint256constant LIST_SIZE_LIMIT_ROUTERS =200;
/**
* @dev The factor for percentage settings. Example: 100 is 0.1%
*/uint256constant MILLIPERCENT_FACTOR =100_000;
/**
* @dev The de facto standard address to denote the native token
*/addressconstant NATIVE_TOKEN_ADDRESS =0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
Contract Source Code
File 4 of 16: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 5 of 16: DataStructures.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;/**
* @notice Optional value structure
* @dev Is used in mappings to allow zero values
* @param isSet Value presence flag
* @param value Numeric value
*/structOptionalValue {
bool isSet;
uint256 value;
}
/**
* @notice Key-to-value structure
* @dev Is used as an array parameter item to perform multiple key-value settings
* @param key Numeric key
* @param value Numeric value
*/structKeyToValue {
uint256 key;
uint256 value;
}
/**
* @notice Key-to-value structure for address values
* @dev Is used as an array parameter item to perform multiple key-value settings with address values
* @param key Numeric key
* @param value Address value
*/structKeyToAddressValue {
uint256 key;
address value;
}
/**
* @notice Address-to-flag structure
* @dev Is used as an array parameter item to perform multiple settings
* @param account Account address
* @param flag Flag value
*/structAccountToFlag {
address account;
bool flag;
}
/**
* @notice Emitted when a list exceeds the size limit
*/errorListSizeLimitError();
/**
* @notice Sets or updates a value in a combined map (a mapping with a key list and key index mapping)
* @param _map The mapping reference
* @param _keyList The key list reference
* @param _keyIndexMap The key list index mapping reference
* @param _key The numeric key
* @param _value The address value
* @param _sizeLimit The map and list size limit
* @return isNewKey True if the key was just added, otherwise false
*/functioncombinedMapSet(mapping(uint256 => address) storage _map,
uint256[] storage _keyList,
mapping(uint256 => OptionalValue) storage _keyIndexMap,
uint256 _key,
address _value,
uint256 _sizeLimit
) returns (bool isNewKey) {
isNewKey =!_keyIndexMap[_key].isSet;
if (isNewKey) {
uniqueListAdd(_keyList, _keyIndexMap, _key, _sizeLimit);
}
_map[_key] = _value;
}
/**
* @notice Removes a value from a combined map (a mapping with a key list and key index mapping)
* @param _map The mapping reference
* @param _keyList The key list reference
* @param _keyIndexMap The key list index mapping reference
* @param _key The numeric key
* @return isChanged True if the combined map was changed, otherwise false
*/functioncombinedMapRemove(mapping(uint256 => address) storage _map,
uint256[] storage _keyList,
mapping(uint256 => OptionalValue) storage _keyIndexMap,
uint256 _key
) returns (bool isChanged) {
isChanged = _keyIndexMap[_key].isSet;
if (isChanged) {
delete _map[_key];
uniqueListRemove(_keyList, _keyIndexMap, _key);
}
}
/**
* @notice Adds a value to a unique value list (a list with value index mapping)
* @param _list The list reference
* @param _indexMap The value index mapping reference
* @param _value The numeric value
* @param _sizeLimit The list size limit
* @return isChanged True if the list was changed, otherwise false
*/functionuniqueListAdd(uint256[] storage _list,
mapping(uint256 => OptionalValue) storage _indexMap,
uint256 _value,
uint256 _sizeLimit
) returns (bool isChanged) {
isChanged =!_indexMap[_value].isSet;
if (isChanged) {
if (_list.length>= _sizeLimit) {
revert ListSizeLimitError();
}
_indexMap[_value] = OptionalValue(true, _list.length);
_list.push(_value);
}
}
/**
* @notice Removes a value from a unique value list (a list with value index mapping)
* @param _list The list reference
* @param _indexMap The value index mapping reference
* @param _value The numeric value
* @return isChanged True if the list was changed, otherwise false
*/functionuniqueListRemove(uint256[] storage _list,
mapping(uint256 => OptionalValue) storage _indexMap,
uint256 _value
) returns (bool isChanged) {
OptionalValue storage indexItem = _indexMap[_value];
isChanged = indexItem.isSet;
if (isChanged) {
uint256 itemIndex = indexItem.value;
uint256 lastIndex = _list.length-1;
if (itemIndex != lastIndex) {
uint256 lastValue = _list[lastIndex];
_list[itemIndex] = lastValue;
_indexMap[lastValue].value= itemIndex;
}
_list.pop();
delete _indexMap[_value];
}
}
/**
* @notice Adds a value to a unique address value list (a list with value index mapping)
* @param _list The list reference
* @param _indexMap The value index mapping reference
* @param _value The address value
* @param _sizeLimit The list size limit
* @return isChanged True if the list was changed, otherwise false
*/functionuniqueAddressListAdd(address[] storage _list,
mapping(address => OptionalValue) storage _indexMap,
address _value,
uint256 _sizeLimit
) returns (bool isChanged) {
isChanged =!_indexMap[_value].isSet;
if (isChanged) {
if (_list.length>= _sizeLimit) {
revert ListSizeLimitError();
}
_indexMap[_value] = OptionalValue(true, _list.length);
_list.push(_value);
}
}
/**
* @notice Removes a value from a unique address value list (a list with value index mapping)
* @param _list The list reference
* @param _indexMap The value index mapping reference
* @param _value The address value
* @return isChanged True if the list was changed, otherwise false
*/functionuniqueAddressListRemove(address[] storage _list,
mapping(address => OptionalValue) storage _indexMap,
address _value
) returns (bool isChanged) {
OptionalValue storage indexItem = _indexMap[_value];
isChanged = indexItem.isSet;
if (isChanged) {
uint256 itemIndex = indexItem.value;
uint256 lastIndex = _list.length-1;
if (itemIndex != lastIndex) {
address lastValue = _list[lastIndex];
_list[itemIndex] = lastValue;
_indexMap[lastValue].value= itemIndex;
}
_list.pop();
delete _indexMap[_value];
}
}
/**
* @notice Adds or removes a value to/from a unique address value list (a list with value index mapping)
* @dev The list size limit is checked on items adding only
* @param _list The list reference
* @param _indexMap The value index mapping reference
* @param _value The address value
* @param _flag The value inclusion flag
* @param _sizeLimit The list size limit
* @return isChanged True if the list was changed, otherwise false
*/functionuniqueAddressListUpdate(address[] storage _list,
mapping(address => OptionalValue) storage _indexMap,
address _value,
bool _flag,
uint256 _sizeLimit
) returns (bool isChanged) {
return
_flag
? uniqueAddressListAdd(_list, _indexMap, _value, _sizeLimit)
: uniqueAddressListRemove(_list, _indexMap, _value);
}
Contract Source Code
File 6 of 16: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
}
Contract Source Code
File 7 of 16: IRevenueShare.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.19;/**
* @title IRevenueShare
* @notice Revenue share interface
*/interfaceIRevenueShare{
/**
* @notice Withdraws tokens
*/functionwithdraw() external;
/**
* @notice Locks tokens
* @param _amount The number of tokens to lock
*/functionlock(uint256 _amount) external;
/**
* @notice Locks tokens on behalf of the user
* @param _amount The number of tokens to lock
* @param _user The address of the user
*/functionlock(uint256 _amount, address _user) external;
}
Contract Source Code
File 8 of 16: ITokenBalance.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;/**
* @title ITokenBalance
* @notice Token balance interface
*/interfaceITokenBalance{
/**
* @notice Getter of the token balance by the account
* @param _account The account address
* @return Token balance
*/functionbalanceOf(address _account) externalviewreturns (uint256);
}
Contract Source Code
File 9 of 16: ManagerRole.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;import { Ownable } from'@openzeppelin/contracts/access/Ownable.sol';
import { RoleBearers } from'./RoleBearers.sol';
/**
* @title ManagerRole
* @notice Base contract that implements the Manager role.
* The manager role is a high-permission role for core team members only.
* Managers can set vaults and routers addresses, fees, cross-chain protocols,
* and other parameters for Interchain (cross-chain) swaps and single-network swaps.
* Please note, the manager role is unique for every contract,
* hence different addresses may be assigned as managers for different contracts.
*/abstractcontractManagerRoleisOwnable, RoleBearers{
bytes32privateconstant ROLE_KEY =keccak256('Manager');
/**
* @notice Emitted when the Manager role status for the account is updated
* @param account The account address
* @param value The Manager role status flag
*/eventSetManager(addressindexed account, boolindexed value);
/**
* @notice Emitted when the Manager role status for the account is renounced
* @param account The account address
*/eventRenounceManagerRole(addressindexed account);
/**
* @notice Emitted when the caller is not a Manager role bearer
*/errorOnlyManagerError();
/**
* @dev Modifier to check if the caller is a Manager role bearer
*/modifieronlyManager() {
if (!isManager(msg.sender)) {
revert OnlyManagerError();
}
_;
}
/**
* @notice Updates the Manager role status for the account
* @param _account The account address
* @param _value The Manager role status flag
*/functionsetManager(address _account, bool _value) publiconlyOwner{
_setRoleBearer(ROLE_KEY, _account, _value);
emit SetManager(_account, _value);
}
/**
* @notice Renounces the Manager role
*/functionrenounceManagerRole() externalonlyManager{
_setRoleBearer(ROLE_KEY, msg.sender, false);
emit RenounceManagerRole(msg.sender);
}
/**
* @notice Getter of the Manager role bearer count
* @return The Manager role bearer count
*/functionmanagerCount() externalviewreturns (uint256) {
return _roleBearerCount(ROLE_KEY);
}
/**
* @notice Getter of the complete list of the Manager role bearers
* @return The complete list of the Manager role bearers
*/functionfullManagerList() externalviewreturns (address[] memory) {
return _fullRoleBearerList(ROLE_KEY);
}
/**
* @notice Getter of the Manager role bearer status
* @param _account The account address
*/functionisManager(address _account) publicviewreturns (bool) {
return _isRoleBearer(ROLE_KEY, _account);
}
function_initRoles(address _owner,
address[] memory _managers,
bool _addOwnerToManagers
) internal{
address ownerAddress = _owner ==address(0) ? msg.sender : _owner;
for (uint256 index; index < _managers.length; index++) {
setManager(_managers[index], true);
}
if (_addOwnerToManagers &&!isManager(ownerAddress)) {
setManager(ownerAddress, true);
}
if (ownerAddress !=msg.sender) {
transferOwnership(ownerAddress);
}
}
}
Contract Source Code
File 10 of 16: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
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.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 11 of 16: Pausable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/abstractcontractPausableisContext{
/**
* @dev Emitted when the pause is triggered by `account`.
*/eventPaused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/eventUnpaused(address account);
boolprivate _paused;
/**
* @dev Initializes the contract in unpaused state.
*/constructor() {
_paused =false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/modifierwhenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/modifierwhenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/functionpaused() publicviewvirtualreturns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/function_requireNotPaused() internalviewvirtual{
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/function_requirePaused() internalviewvirtual{
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/function_pause() internalvirtualwhenNotPaused{
_paused =true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/function_unpause() internalvirtualwhenPaused{
_paused =false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/draft-IERC20Permit.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
functionsafeTransfer(
IERC20 token,
address to,
uint256 value
) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
functionsafeTransferFrom(
IERC20 token,
addressfrom,
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.
*/functionsafeApprove(
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));
}
functionsafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
functionsafeDecreaseAllowance(
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));
}
}
functionsafePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal{
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore +1, "SafeERC20: permit did not succeed");
}
/**
* @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, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length>0) {
// Return data is optionalrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 14 of 16: StablecoinFarm.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.19;import'@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import'@openzeppelin/contracts/token/ERC20/IERC20.sol';
import { Pausable } from'../Pausable.sol';
import { BalanceManagement } from'../BalanceManagement.sol';
import { IRevenueShare } from'../interfaces/IRevenueShare.sol';
contractStablecoinFarmisPausable, BalanceManagement{
usingSafeERC20forIERC20;
structVestedBalance {
uint256 amount;
uint256 unlockTime;
}
// Info of each user.structUserInfo {
uint256 amount; // How many tokens the user has provided.uint256 rewardDebt; // Reward debt. See the explanation below.uint256 remainingRewardTokenAmount; // Tokens that weren't distributed for a user per pool.// Any point in time, the amount of reward tokens entitled to a user but pending to be distributed is:// pending reward = (user.amount * pool.accumulatedRewardTokenPerShare) - user.rewardDebt//// Whenever a user deposits or withdraws Staked tokens to a pool. Here's what happens:// 1. The pool's `accumulatedRewardTokenPerShare` (and `lastRewardTime`) gets updated.// 2. A user receives the pending reward sent to his/her address.// 3. The user's `amount` gets updated.// 4. The user's `rewardDebt` gets updated.
}
// Info of each pool.structPoolInfo {
address stakingToken; // Contract address of staked tokenuint256 stakingTokenTotalAmount; //Total amount of deposited tokensuint256 accumulatedRewardTokenPerShare; // Accumulated reward token per share, times 1e12. See below.uint32 lastRewardTime; // Last timestamp number that reward token distribution occurs.uint16 allocationPoint; // How many allocation points are assigned to this pool.
}
addresspublicimmutable rewardToken; // The reward token.addresspublic treasury; // The penalty address of the treasury.addresspublic LPRevenueShare; // The penalty address of the fee LPRevenueShare contract.uint256public rewardTokenPerSecond; // Reward tokens vested per second.
PoolInfo[] public poolInfo; // Info of each pool.mapping(address=>bool) public isStakingTokenSet;
mapping(uint256=>mapping(address=> UserInfo)) public userInfo; // Info of each user that stakes tokens.mapping(uint256=>mapping(address=> VestedBalance[])) public userVested; // vested tokensuint256public totalAllocationPoint =0; // the sum of all allocation points in all pools.uint32publicimmutable startTime; // the timestamp when reward token farming starts.uint32public endTime; // time on which the reward calculation should end.uint256publicimmutable vestingDuration;
uint256public exitEarlyUserShare =500; // 50%uint256public exitEarlyTreasuryShare =200; // 20%uint256public exitEarlyLPShare =300; // 30%// Factor to perform multiplication and division operations.uint256privateconstant SHARE_PRECISION =1e18;
eventStaked(addressindexed user, uint256indexed pid, uint256 amount);
eventWithdraw(addressindexed user, uint256indexed pid, uint256 amount);
eventEmergencyWithdraw(addressindexed user, uint256indexed pid, uint256 amount);
eventWithdrawVesting(addressindexed user, uint256 amount);
eventVested(addressindexed user, uint256indexed pid, uint256 amount);
eventLocked(addressindexed user, uint256indexed pid, uint256 amount);
eventExitEarly(addressindexed user, uint256 amount);
constructor(address _rewardToken,
uint256 _rewardTokenPerSecond,
uint32 _startTime,
uint32 _endTimeAddSeconds,
uint256 _vestingDuration
) {
rewardToken = _rewardToken;
rewardTokenPerSecond = _rewardTokenPerSecond;
startTime = _startTime;
endTime = startTime + _endTimeAddSeconds;
vestingDuration = _vestingDuration;
}
/**
* @dev Sets a new treasury
* @param _newTreasury is a new treasury address
*/functionsetTreasury(address _newTreasury) externalonlyOwner{
require(_newTreasury !=address(0), 'Zero address error');
treasury = _newTreasury;
}
/**
* @dev Sets a new LP revenue share
* @param _newRevenueShare is a new LP revenue share address
*/functionsetLPRevenueShare(address _newRevenueShare) externalonlyOwner{
require(_newRevenueShare !=address(0), 'Zero address error');
LPRevenueShare = _newRevenueShare;
}
/**
* @dev Sets portions for exit early. If it needs to set 33.3%, just provide a 333 value.
* Pay attention, the sum of all values must be 1000, which means 100%
* @param _userPercent is a user percent
* @param _treasuryPercent is a treasury percent
* @param _lpPercent is an LP share percent
*/functionsetPercentsShare(uint256 _userPercent,
uint256 _treasuryPercent,
uint256 _lpPercent
) externalonlyOwner{
require(
_userPercent + _treasuryPercent + _lpPercent ==1000,
'Total percentage should be 100% in total'
);
exitEarlyUserShare = _userPercent;
exitEarlyTreasuryShare = _treasuryPercent;
exitEarlyLPShare = _lpPercent;
}
/**
* @dev Deposit staking tokens for reward token allocation.
* @param _pid is a pool id
* @param _amount is a number of deposit tokens
*/functionstake(uint256 _pid, uint256 _amount) externalwhenNotPaused{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
_updatePool(_pid);
IERC20(pool.stakingToken).safeTransferFrom(msg.sender, address(this), _amount);
user.remainingRewardTokenAmount = pendingRewardToken(_pid, msg.sender);
user.amount += _amount;
pool.stakingTokenTotalAmount += _amount;
user.rewardDebt = (user.amount * pool.accumulatedRewardTokenPerShare) / SHARE_PRECISION;
emit Staked(msg.sender, _pid, _amount);
}
/**
* @dev Withdraw only staked iUSDC/iUSDT tokens
* @param _pid is a pool id
* @param _amount is an amount of withdrawn tokens
*/functionwithdraw(uint256 _pid, uint256 _amount) externalwhenNotPaused{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount < _amount) {
revert('Can not withdraw this amount');
}
_updatePool(_pid);
user.remainingRewardTokenAmount = pendingRewardToken(_pid, msg.sender);
user.amount -= _amount;
pool.stakingTokenTotalAmount -= _amount;
user.rewardDebt = (user.amount * pool.accumulatedRewardTokenPerShare) / SHARE_PRECISION;
IERC20(pool.stakingToken).safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
/**
* @dev Withdraw without caring about rewards. EMERGENCY ONLY.
* @param _pid is a pool id
*/functionemergencyWithdraw(uint256 _pid) external{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 userAmount = user.amount;
pool.stakingTokenTotalAmount -= userAmount;
user.amount =0;
user.rewardDebt =0;
user.remainingRewardTokenAmount =0;
IERC20(pool.stakingToken).safeTransfer(msg.sender, userAmount);
emit EmergencyWithdraw(msg.sender, _pid, userAmount);
}
/**
* @dev Add seconds to endTime parameter
* @param _addSeconds is an additional seconds value
*/functionchangeEndTime(uint32 _addSeconds) externalonlyManager{
endTime += _addSeconds;
}
/**
* @dev Changes reward token amount per second. Use this function to moderate the `lockup amount`.
* Essentially this function changes the amount of the reward which is entitled to the user
* for his token staking by the time the `endTime` is passed.
* Good practice to update pools without messing up the contract.
* @param _rewardTokenPerSecond is a new value for reward token per second
* @param _withUpdate if set in true all pools will be updated,
* otherwise only new rewardTokenPerSecond will be set
*/functionsetRewardTokenPerSecond(uint256 _rewardTokenPerSecond,
bool _withUpdate
) externalonlyManager{
if (_withUpdate) {
_massUpdatePools();
}
rewardTokenPerSecond = _rewardTokenPerSecond;
}
/**
* @dev Add a new staking token to the pool. Can only be called by managers.
* @param _allocPoint is an allocation point
* @param _stakingToken is a staked token address that will be used for the new pool
* @param _withUpdate if set in true all pools will be updated,
* otherwise only the new pool will be added
*/functionadd(uint16 _allocPoint, address _stakingToken, bool _withUpdate) externalonlyManager{
require(!isStakingTokenSet[_stakingToken], 'Staking token was already set');
require(poolInfo.length<5, 'No more then 5 pools can be added');
if (_withUpdate) {
_massUpdatePools();
}
uint256 lastRewardTime =block.timestamp> startTime ? block.timestamp : startTime;
totalAllocationPoint += _allocPoint;
poolInfo.push(
PoolInfo({
stakingToken: _stakingToken,
stakingTokenTotalAmount: 0,
allocationPoint: _allocPoint,
lastRewardTime: uint32(lastRewardTime),
accumulatedRewardTokenPerShare: 0
})
);
isStakingTokenSet[_stakingToken] =true;
}
/**
* @dev Update the given pool's reward token allocation point. Can only be called by managers.
* @param _pid is a pool id that exists in the list
* @param _allocPoint is an allocation point
* @param _withUpdate if set in true all pools will be updated,
* otherwise only allocation data will be updated
*/functionset(uint256 _pid, uint16 _allocPoint, bool _withUpdate) externalonlyManager{
if (_withUpdate) {
_massUpdatePools();
}
totalAllocationPoint = totalAllocationPoint - poolInfo[_pid].allocationPoint + _allocPoint;
poolInfo[_pid].allocationPoint = _allocPoint;
}
/**
* @dev Update reward variables for all pools.
*/functionmassUpdatePools() externalwhenNotPaused{
_massUpdatePools();
}
/**
* @dev Update reward variables of the given pool to be up-to-date.
*/functionupdatePool(uint256 _pid) externalwhenNotPaused{
_updatePool(_pid);
}
/**
* @dev How many pools are in the contract
*/functionpoolLength() externalviewreturns (uint256) {
return poolInfo.length;
}
/**
* @dev Vest all pending rewards. Vest tokens means that they will be locked for the
* vestingDuration time
* @param _pid is a pool id
*/functionvest(uint256 _pid) externalwhenNotPaused{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
_updatePool(_pid);
uint256 pending = pendingRewardToken(_pid, msg.sender);
require(pending >0, 'Amount of tokens can not be zero value');
uint256 unlockTime =block.timestamp+ vestingDuration;
VestedBalance[] storage vestings = userVested[_pid][msg.sender];
require(vestings.length<=100, 'User can not execute vest function more than 100 times');
vestings.push(VestedBalance({ amount: pending, unlockTime: unlockTime }));
user.remainingRewardTokenAmount =0;
user.rewardDebt = (user.amount * pool.accumulatedRewardTokenPerShare) / SHARE_PRECISION;
emit Vested(msg.sender, _pid, pending);
}
/**
* @dev user can get his rewards for staked iUSDC/iUSDT if locked time has already occurred
* @param _pid is a pool id
*/functionwithdrawVestedRewards(uint256 _pid) external{
// withdraw only `vestedTotal` amount
_updatePool(_pid);
(uint256 vested, , ) = checkVestingBalances(_pid, msg.sender);
uint256 amount;
if (vested >0) {
uint256 length = userVested[_pid][msg.sender].length;
for (uint256 i =0; i < length; i++) {
uint256 vestAmount = userVested[_pid][msg.sender][i].amount;
if (userVested[_pid][msg.sender][i].unlockTime >block.timestamp) {
break;
}
amount = amount + vestAmount;
delete userVested[_pid][msg.sender][i];
}
}
if (amount >0) {
safeRewardTransfer(msg.sender, amount);
} else {
revert('Tokens are not available for now');
}
emit WithdrawVesting(msg.sender, amount);
}
/**
* @dev The user receives only `exitEarlyUserShare` - 50% tokens by default
* `exitEarlyTreasuryShare` - 20% tokens by default transfers to the treasury account
* `exitEarlyLPShare` - 30% tokens by default transfers to the LP revenue share contract
* @param _pid is a pool id
*/functionexitEarly(uint256 _pid) external{
_updatePool(_pid);
// can withdraw 50% immediately
(, uint256 vesting, ) = checkVestingBalances(_pid, msg.sender);
require(vesting >0, 'Total vesting tokens can not be zero');
uint256 amountUser = (vesting * exitEarlyUserShare) /1000;
uint256 amountTreasury = (vesting * exitEarlyTreasuryShare) /1000;
uint256 amountLP = (vesting * exitEarlyLPShare) /1000;
safeRewardTransfer(msg.sender, amountUser);
// transfer penalties
IERC20(rewardToken).safeTransfer(treasury, amountTreasury);
IERC20(rewardToken).safeTransfer(LPRevenueShare, amountLP);
_cleanVestingBalances(_pid, msg.sender);
emit ExitEarly(msg.sender, amountUser);
}
/**
* @dev Unsupported operation
* @param _pid is a pool id
*/functionlockVesting(uint256 _pid) external{
revert('Unsupported operation');
}
/**
* @dev Unsupported operation
* @param _pid is a pool id
*/functionlockPending(uint256 _pid) external{
revert('Unsupported operation');
}
/**
* @dev Return reward multiplier over the given _from to _to time.
* @param _from is a from datetime in seconds
* @param _to is a to datetime in seconds
* @return multiplier
*/functiongetMultiplier(uint256 _from, uint256 _to) publicviewreturns (uint256) {
_from = _from > startTime ? _from : startTime;
if (_from > endTime || _to < startTime) {
return0;
} elseif (_to > endTime) {
return endTime - _from;
} elsereturn _to - _from;
}
/**
* @dev Check if provided token is staked token in the pool
* @param _tokenAddress is a checked token
* @return result true if provided token is staked token in the pool, otherwise false
*/functionisReservedToken(address _tokenAddress) publicviewoverridereturns (bool) {
uint256 length = poolInfo.length;
for (uint256 pid; pid < length; ++pid) {
if (_tokenAddress == poolInfo[pid].stakingToken) {
returntrue;
}
}
returnfalse;
}
/**
* @dev View function to see pending reward tokens on the frontend.
* @param _pid is a pool id
* @param _user is a user address to check rewards
* @return pending reward token amount
*/functionpendingRewardToken(uint256 _pid, address _user) publicviewreturns (uint256 pending) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 acc = pool.accumulatedRewardTokenPerShare;
if (block.timestamp> pool.lastRewardTime && pool.stakingTokenTotalAmount !=0) {
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 tokenReward = (multiplier * rewardTokenPerSecond * pool.allocationPoint) /
totalAllocationPoint;
acc += (tokenReward * SHARE_PRECISION) / pool.stakingTokenTotalAmount;
}
pending =
(user.amount * acc) /
SHARE_PRECISION -
user.rewardDebt +
user.remainingRewardTokenAmount;
}
/**
* @dev Information on a user's total/vestedTotal/vestingTotal balances
* @param _pid is a pool id
* @param _user is a user address to check rewards
* @return vestedTotal is the number of vested tokens (that are available to withdraw)
* @return vestingTotal is the number of vesting tokens (that are not available to withdraw yet)
* @return vestData is the list with the number of tokens and their unlock time
*/functioncheckVestingBalances(uint256 _pid,
address _user
)
publicviewreturns (uint256 vestedTotal, // available to withdrawuint256 vestingTotal,
VestedBalance[] memory vestData
)
{
VestedBalance[] storage vests = userVested[_pid][_user];
uint256 index;
for (uint256 i =0; i < vests.length; i++) {
if (vests[i].unlockTime >block.timestamp) {
if (index ==0) {
vestData =new VestedBalance[](vests.length- i);
}
vestData[index] = vests[i];
index++;
vestingTotal += vests[i].amount;
} else {
vestedTotal = vestedTotal + vests[i].amount;
}
}
}
function_cleanVestingBalances(uint256 _pid, address _user) internal{
VestedBalance[] storage vests = userVested[_pid][_user];
for (uint256 i =0; i < vests.length; i++) {
if (vests[i].unlockTime >block.timestamp) {
delete vests[i];
}
}
}
/**
* @dev Safe reward token transfer function.
* Revert error if not enough tokens on the smart contract
* Just in case the pool does not have enough reward tokens.
* @param _to is an address to transfer rewards
* @param _amount is a number of reward tokens that will be transferred to the user
*/functionsafeRewardTransfer(address _to, uint256 _amount) private{
uint256 rewardTokenBalance = IERC20(rewardToken).balanceOf(address(this));
if (_amount > rewardTokenBalance) {
revert('Not enough tokens on the smart contract');
} else {
IERC20(rewardToken).safeTransfer(_to, _amount);
}
}
/**
* @dev Update reward variables for all pools
*/function_massUpdatePools() private{
uint256 length = poolInfo.length;
for (uint256 pid; pid < length; ++pid) {
_updatePool(pid);
}
}
/**
* @dev Update reward variables of the given pool to be up-to-date.
* @param _pid is a pool id
*/function_updatePool(uint256 _pid) private{
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp<= pool.lastRewardTime) {
return;
}
if (pool.stakingTokenTotalAmount ==0) {
pool.lastRewardTime =uint32(block.timestamp);
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 rewardTokenAmount = (multiplier * rewardTokenPerSecond * pool.allocationPoint) /
totalAllocationPoint;
pool.accumulatedRewardTokenPerShare +=
(rewardTokenAmount * SHARE_PRECISION) /
pool.stakingTokenTotalAmount;
pool.lastRewardTime =uint32(block.timestamp);
}
}
Contract Source Code
File 15 of 16: TransferHelper.sol
// SPDX-License-Identifier: AGPL-3.0-onlypragmasolidity 0.8.19;/**
* @notice Emitted when an approval action fails
*/errorSafeApproveError();
/**
* @notice Emitted when a transfer action fails
*/errorSafeTransferError();
/**
* @notice Emitted when a transferFrom action fails
*/errorSafeTransferFromError();
/**
* @notice Emitted when a transfer of the native token fails
*/errorSafeTransferNativeError();
/**
* @notice Safely approve the token to the account
* @param _token The token address
* @param _to The token approval recipient address
* @param _value The token approval amount
*/functionsafeApprove(address _token, address _to, uint256 _value) {
// 0x095ea7b3 is the selector for "approve(address,uint256)"
(bool success, bytesmemory data) = _token.call(
abi.encodeWithSelector(0x095ea7b3, _to, _value)
);
bool condition = success && (data.length==0||abi.decode(data, (bool)));
if (!condition) {
revert SafeApproveError();
}
}
/**
* @notice Safely transfer the token to the account
* @param _token The token address
* @param _to The token transfer recipient address
* @param _value The token transfer amount
*/functionsafeTransfer(address _token, address _to, uint256 _value) {
// 0xa9059cbb is the selector for "transfer(address,uint256)"
(bool success, bytesmemory data) = _token.call(
abi.encodeWithSelector(0xa9059cbb, _to, _value)
);
bool condition = success && (data.length==0||abi.decode(data, (bool)));
if (!condition) {
revert SafeTransferError();
}
}
/**
* @notice Safely transfer the token between the accounts
* @param _token The token address
* @param _from The token transfer source address
* @param _to The token transfer recipient address
* @param _value The token transfer amount
*/functionsafeTransferFrom(address _token, address _from, address _to, uint256 _value) {
// 0x23b872dd is the selector for "transferFrom(address,address,uint256)"
(bool success, bytesmemory data) = _token.call(
abi.encodeWithSelector(0x23b872dd, _from, _to, _value)
);
bool condition = success && (data.length==0||abi.decode(data, (bool)));
if (!condition) {
revert SafeTransferFromError();
}
}
/**
* @notice Safely transfer the native token to the account
* @param _to The native token transfer recipient address
* @param _value The native token transfer amount
*/functionsafeTransferNative(address _to, uint256 _value) {
(bool success, ) = _to.call{ value: _value }(newbytes(0));
if (!success) {
revert SafeTransferNativeError();
}
}
Contract Source Code
File 16 of 16: draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}