// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)pragmasolidity ^0.8.20;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/errorAddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/errorAddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/errorFailedInnerCall();
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
if (address(this).balance< amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
if (address(this).balance< value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata
) internalviewreturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty// otherwise we already know that it was a contractif (returndata.length==0&& target.code.length==0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/functionverifyCallResult(bool success, bytesmemory returndata) internalpurereturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/function_revert(bytesmemory returndata) 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 FailedInnerCall();
}
}
}
Contract Source Code
File 2 of 11: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)pragmasolidity ^0.8.20;/**
* @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;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @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 value of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) externalreturns (bool);
}
Contract Source Code
File 5 of 11: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.20;/**
* @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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/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].
*
* CAUTION: See Security Considerations above.
*/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);
}
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗//██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║//██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║//██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║//██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║//╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝//SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.8.20;import {IERC20} from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ILootVoteController} from"./interfaces/ILootVoteController.sol";
import {IHolyPalPower} from"./interfaces/IHolyPalPower.sol";
import"./libraries/Errors.sol";
import"./utils/Owner.sol";
/** @title Loot Vote Controller contract *//// @author Paladin/*
Contract handling the vote logic for repartition of the global Loot budget
between all the listed gauges for the Quest system
*/contractLootVoteControllerisOwner, ILootVoteController{
usingSafeERC20forIERC20;
// Constants/** @notice Seconds in a Week */uint256privateconstant WEEK =604800;
/** @notice Unit scale for wei calculations */uint256privateconstant UNIT =1e18;
/** @notice Max BPS value */uint256privateconstant MAX_BPS =10000;
/** @notice Cooldown between 2 votes */uint256privateconstant VOTE_COOLDOWN =864000; // 10 days/** @notice Max number of votes an user can vote at once */uint256privateconstant MAX_VOTE_LENGTH =10;
/** @notice Max number of proxies an user can have at once */uint256privateconstant MAX_PROXY_LENGTH =50;
uint256privateconstant MIN_GAUGE_CAP =0.001*1e18; // 0.1%uint256privateconstant MAX_GAUGE_CAP =1*1e18; // 100%// Structs/** @notice Quest Board & distributor struct */structQuestBoard {
address board;
address distributor;
}
/** @notice Point struct */structPoint {
uint256 bias;
uint256 slope;
}
/** @notice Voted Slope struct */structVotedSlope {
uint256 slope;
uint256 power;
uint256 end;
address caller;
}
/** @notice Struct used for the vote method */structVoteVars {
uint256 currentPeriod;
uint256 nextPeriod;
int128 userSlope;
uint256 userLockEnd;
uint256 oldBias;
uint256 newBias;
uint256 totalPowerUsed;
uint256 oldUsedPower;
uint256 oldWeightBias;
uint256 oldWeightSlope;
uint256 oldTotalBias;
uint256 oldTotalSlope;
}
/** @notice Proxy Voter struct */structProxyVoter {
uint256 maxPower;
uint256 usedPower;
uint256 endTimestamp;
}
// Storage/** @notice Address of the hPalPower contract */addresspublicimmutable hPalPower;
/** @notice Next ID to list Boards */uint256public nextBoardId; // ID 0 == no ID/not set/** @notice Listed Quest Boards */mapping(uint256=> QuestBoard) public questBoards;
/** @notice Match Board address to ID */mapping(address=>uint256) public boardToId;
/** @notice Match Distributor address to ID */mapping(address=>uint256) public distributorToId;
/** @notice Match a Gauge to a Board ID */mapping(address=>uint256) public gaugeToBoardId;
/** @notice Default weight cap for gauges */uint256public defaultCap =0.1*1e18; // 10%/** @notice Custom caps for gauges */mapping(address=>uint256) public gaugeCaps;
/** @notice Flag for killed gauges */mapping(address=>bool) public isGaugeKilled;
/** @notice User VotedSlopes for each gauge */// user -> gauge -> VotedSlopemapping(address=>mapping(address=> VotedSlope)) public voteUserSlopes;
/** @notice Total vote power used by user */mapping(address=>uint256) public voteUserPower;
/** @notice Last user vote's timestamp for each gauge address */mapping(address=>mapping(address=>uint256)) public lastUserVote;
/** @notice Point weight for each gauge */// gauge -> time -> Pointmapping(address=>mapping(uint256=> Point)) public pointsWeight;
/** @notice Slope changes for each gauge */// gauge -> time -> slopemapping(address=>mapping(uint256=>uint256)) public changesWeight;
/** @notice Last scheduled time for gauge weight update */// gauge -> last scheduled time (next week)mapping(address=>uint256) public timeWeight;
/** @notice Total Point weights */// time -> Pointmapping(uint256=> Point) public pointsWeightTotal;
/** @notice Total weight slope changes */// time -> slopemapping(uint256=>uint256) public changesWeightTotal;
/** @notice Last scheduled time for weight update */uint256public timeTotal;
/** @notice Proxy Managers set for each user */// user -> proxy manager -> boolmapping(address=>mapping(address=>bool)) public isProxyManager;
/** @notice Max Proxy duration allowed for Manager */// user -> proxy manager -> uint256mapping(address=>mapping(address=>uint256)) public maxProxyDuration;
/** @notice State of Proxy Managers for each user */// user -> proxy voter -> statemapping(address=>mapping(address=> ProxyVoter)) public proxyVoterState;
/** @notice List of current proxy for each user */mapping(address=>address[]) public currentUserProxyVoters;
/** @notice Blocked (for Proxies) voting power for each user */mapping(address=>uint256) public blockedProxyPower;
/** @notice Used free voting power for each user */mapping(address=>uint256) public usedFreePower;
// Events/** @notice Event emitted when a vote is casted for a gauge */eventVoteForGauge(uint256 time,
address user,
address gauge_addr,
uint256 weight
);
/** @notice Event emitted when a new Board is listed */eventNewBoardListed(uint256 id, addressindexed board, addressindexed distributor);
/** @notice Event emitted when a Board is udpated */eventBoardUpdated(uint256 id, addressindexed newDistributor);
/** @notice Event emitted when a new Gauge is listed */eventNewGaugeAdded(addressindexed gauge, uint256indexed boardId, uint256 cap);
/** @notice Event emitted when a Gauge is updated */eventGaugeCapUpdated(addressindexed gauge, uint256indexed boardId, uint256 newCap);
/** @notice Event emitted when a Gauge is updated */eventGaugeBoardUpdated(addressindexed gauge, uint256indexed newBoardId);
/** @notice Event emitted when a Gauge is killed */eventGaugeKilled(addressindexed gauge, uint256indexed boardId);
/** @notice Event emitted when a Gauge is unkilled */eventGaugeUnkilled(addressindexed gauge, uint256indexed boardId);
/** @notice Event emitted when a Proxy Manager is set */eventSetProxyManager(addressindexed user, addressindexed manager);
/** @notice Event emitted when a Proxy Manager is removed */eventRemoveProxyManager(addressindexed user, addressindexed manager);
/** @notice Event emitted when a Proxy Voter is set */eventSetNewProxyVoter(addressindexed user, addressindexed proxyVoter, uint256 maxPower, uint256 endTimestamp);
/** @notice Event emitted when the default gauge cap is updated */eventDefaultCapUpdated(uint256 newCap);
// Constructorconstructor(address _hPalPower) {
if(_hPalPower ==address(0)) revert Errors.AddressZero();
hPalPower = _hPalPower;
nextBoardId =1;
timeTotal = (block.timestamp) / WEEK * WEEK;
}
// View functions/**
* @notice Is the gauge listed
* @param gauge Address of the gauge
* @return bool : Is the gauge listed
*/functionisListedGauge(address gauge) externalviewreturns(bool) {
return _isGaugeListed(gauge);
}
/**
* @notice Returns the Quest Board assocatied to a gauge
* @param gauge Address of the gauge
* @return address : Address of the Quest Board
*/functiongetBoardForGauge(address gauge) externalviewreturns(address) {
return questBoards[gaugeToBoardId[gauge]].board;
}
/**
* @notice Returns the Distributor assocatied to a gauge
* @param gauge Address of the gauge
* @return address : Address of the Distributor
*/functiongetDistributorForGauge(address gauge) externalviewreturns(address) {
return questBoards[gaugeToBoardId[gauge]].distributor;
}
/**
* @notice Returns the current gauge weight
* @param gauge Address of the gauge
* @return uint256 : Current gauge weight
*/functiongetGaugeWeight(address gauge) externalviewreturns(uint256) {
return pointsWeight[gauge][timeWeight[gauge]].bias;
}
/**
* @notice Returns the gauge weight at a specific timestamp
* @param gauge Address of the gauge
* @param ts Timestamp
* @return uint256 : Gauge weight at the timestamp
*/functiongetGaugeWeightAt(address gauge, uint256 ts) externalviewreturns(uint256) {
ts = ts / WEEK * WEEK;
return pointsWeight[gauge][ts].bias;
}
/**
* @notice Returns the current total weight
* @return uint256 : Total weight
*/functiongetTotalWeight() externalviewreturns(uint256) {
return pointsWeightTotal[timeTotal].bias;
}
/**
* @notice Returns a gauge relative weight
* @param gauge Address of the gauge
* @return uint256 : Gauge relative weight
*/functiongetGaugeRelativeWeight(address gauge) externalviewreturns(uint256) {
return _getGaugeRelativeWeight(gauge, block.timestamp);
}
/**
* @notice Returns a gauge relative weight at a specific timestamp
* @param gauge Address of the gauge
* @param ts Timestamp
* @return uint256 : Gauge relative weight at the timestamp
*/functiongetGaugeRelativeWeight(address gauge, uint256 ts) externalviewreturns(uint256) {
return _getGaugeRelativeWeight(gauge, ts);
}
/**
* @notice Returns the cap relative weight for a gauge
* @param gauge Address of the gauge
* @return uint256 : Gauge cap
*/functiongetGaugeCap(address gauge) externalviewreturns(uint256) {
return gaugeCaps[gauge] !=0 ? gaugeCaps[gauge] : defaultCap;
}
/**
* @notice Returns the list of current proxies for a user
* @param user Address of the user
* @return address[] : List of proxy addresses
*/functiongetUserProxyVoters(address user) externalviewreturns(address[] memory) {
return currentUserProxyVoters[user];
}
// State-changing functions/**
* @notice Votes for a gauge weight
* @dev Votes for a gauge weight based on the given user power
* @param gauge Address of the gauge
* @param userPower Power used for this gauge
*/functionvoteForGaugeWeights(address gauge, uint256 userPower) external{
// Clear any expired past Proxy
_clearExpiredProxies(msg.sender);
_voteForGauge(msg.sender, gauge, userPower, msg.sender);
}
/**
* @notice Votes for multiple gauge weights
* @dev Votes for multiple gauge weights based on the given user powers
* @param gauge Address of the gauges
* @param userPower Power used for each gauge
*/functionvoteForManyGaugeWeights(address[] calldata gauge, uint256[] calldata userPower) external{
// Clear any expired past Proxy
_clearExpiredProxies(msg.sender);
uint256 length = gauge.length;
if(length > MAX_VOTE_LENGTH) revert Errors.MaxVoteListExceeded();
if(length != userPower.length) revert Errors.ArraySizeMismatch();
for(uint256 i; i < length; i++) {
_voteForGauge(msg.sender, gauge[i], userPower[i], msg.sender);
}
}
/**
* @notice Votes for a gauge weight as another user
* @dev Votes for a gauge weight based on the given user power as another user (need to have a proxy set)
* @param user Address of the user
* @param gauge Address of the gauge
* @param userPower Power used for this gauge
*/functionvoteForGaugeWeightsFor(address user, address gauge, uint256 userPower) external{
// Clear any expired past Proxy
_clearExpiredProxies(user);
ProxyVoter memory proxyState = proxyVoterState[user][msg.sender];
if(proxyState.maxPower ==0) revert Errors.NotAllowedProxyVoter();
if(proxyState.endTimestamp <block.timestamp) revert Errors.ExpiredProxy();
if(userPower > proxyState.maxPower) revert Errors.VotingPowerProxyExceeded();
_voteForGauge(user, gauge, userPower, msg.sender);
}
/**
* @notice Votes for multiple gauge weights as another user
* @dev Votes for multiple gauge weights based on the given user powers as another user (need to have a proxy set)
* @param user Address of the user
* @param gauge Address of the gauges
* @param userPower Power used for each gauge
*/functionvoteForManyGaugeWeightsFor(address user, address[] calldata gauge, uint256[] calldata userPower) external{
// Clear any expired past Proxy
_clearExpiredProxies(user);
ProxyVoter memory proxyState = proxyVoterState[user][msg.sender];
if(proxyState.maxPower ==0) revert Errors.NotAllowedProxyVoter();
if(proxyState.endTimestamp <block.timestamp) revert Errors.ExpiredProxy();
uint256 totalPower;
uint256 length = gauge.length;
if(length > MAX_VOTE_LENGTH) revert Errors.MaxVoteListExceeded();
if(length != userPower.length) revert Errors.ArraySizeMismatch();
for(uint256 i; i < length;) {
totalPower += userPower[i];
_voteForGauge(user, gauge[i], userPower[i], msg.sender);
unchecked { i++; }
}
if(totalPower > proxyState.maxPower) revert Errors.VotingPowerProxyExceeded();
}
/**
* @notice Returns the updated gauge relative weight
* @dev Updates the gauge weight & returns the new relative weight
* @param gauge Address of the gauge
* @return uint256 : Updated gauge relative weight
*/functiongetGaugeRelativeWeightWrite(address gauge) externalreturns(uint256) {
_updateGaugeWeight(gauge);
_updateTotalWeight();
return _getGaugeRelativeWeight(gauge, block.timestamp);
}
/**
* @notice Returns the updated gauge relative weight at a given timestamp
* @dev Updates the gauge weight & returns the relative weight at a given timestamp
* @param gauge Address of the gauge
* @param ts Timestamp
* @return uint256 : Updated gauge relative weight at the timestamp
*/functiongetGaugeRelativeWeightWrite(address gauge, uint256 ts) externalreturns(uint256) {
_updateGaugeWeight(gauge);
_updateTotalWeight();
return _getGaugeRelativeWeight(gauge, ts);
}
/**
* @notice Updates the gauge weight
* @dev Updates a gauge current weight for all past non-updated periods
* @param gauge Address of the gauge
*/functionupdateGaugeWeight(address gauge) external{
_updateGaugeWeight(gauge);
}
/**
* @notice Updates the total weight
* @dev Updates the total wieght for all past non-updated periods
*/functionupdateTotalWeight() external{
_updateTotalWeight();
}
/**
* @notice Approves a Proxy Manager for the caller
* @dev Approves a Proxy Manager for the caller allowed to create Proxy on his voting power
* @param manager Address of the Proxy Manager
* @param maxDuration Maximum Proxy duration allowed to be created by the Manager (can be set to 0 for no limit)
*/functionapproveProxyManager(address manager, uint256 maxDuration) external{
if(manager ==address(0)) revert Errors.AddressZero();
isProxyManager[msg.sender][manager] =true;
maxProxyDuration[msg.sender][manager] = maxDuration;
emit SetProxyManager(msg.sender, manager);
}
/**
* @notice Updates the max duration allowed for a Proxy Manager
* @dev Updates the max duration allowed for a Proxy Manager
* @param manager Address of the Proxy Manager
* @param newMaxDuration Maximum Proxy duration allowed to be created by the Manager (can be set to 0 for no limit)
*/functionupdateProxyManagerDuration(address manager, uint256 newMaxDuration) external{
if(manager ==address(0)) revert Errors.AddressZero();
if(!isProxyManager[msg.sender][manager]) revert Errors.NotAllowedManager();
maxProxyDuration[msg.sender][manager] = newMaxDuration;
}
/**
* @notice Approves a Proxy Manager for the caller
* @dev Approves a Proxy Manager for the caller allowed to create Proxy on his voting power
* @param manager Address of the Proxy Manager
*/functionremoveProxyManager(address manager) external{
if(manager ==address(0)) revert Errors.AddressZero();
isProxyManager[msg.sender][manager] =false;
emit RemoveProxyManager(msg.sender, manager);
}
/**
* @notice Sets a Proxy Voter for the user
* @dev Sets a Proxy Voter for the user allowed to vote on his behalf
* @param user Address of the user
* @param proxy Address of the Proxy Voter
* @param maxPower Max voting power allowed for the Proxy
* @param endTimestamp Timestamp of the Proxy expiry
*/functionsetVoterProxy(address user, address proxy, uint256 maxPower, uint256 endTimestamp) external{
if(!isProxyManager[user][msg.sender] &&msg.sender!= user) revert Errors.NotAllowedManager();
if(maxPower ==0|| maxPower > MAX_BPS) revert Errors.VotingPowerInvalid();
if(currentUserProxyVoters[user].length+1> MAX_PROXY_LENGTH) revert Errors.MaxProxyListExceeded();
// Round down the end timestamp to weeks & check the user Lock is not expired then
endTimestamp = endTimestamp / WEEK * WEEK;
uint256 userLockEnd = IHolyPalPower(hPalPower).locked__end(user);
if(endTimestamp <block.timestamp|| endTimestamp > userLockEnd) revert Errors.InvalidTimestamp();
uint256 maxDuration = maxProxyDuration[user][msg.sender];
if(maxDuration >0&& endTimestamp >block.timestamp+ maxDuration) revert Errors.ProxyDurationExceeded();
// Clear any expired past Proxy
_clearExpiredProxies(user);
// Revert if the user already has a Proxy with the same address
ProxyVoter memory prevProxyState = proxyVoterState[user][proxy];
if(prevProxyState.maxPower !=0) revert Errors.ProxyAlreadyActive();
// Block the user's power for the Proxy & revert if the user execeed's its voting poweruint256 userBlockedPower = blockedProxyPower[user];
if(userBlockedPower + maxPower > MAX_BPS) revert Errors.ProxyPowerExceeded();
blockedProxyPower[user] = userBlockedPower + maxPower;
// Set up the Proxy
proxyVoterState[user][proxy] = ProxyVoter({
maxPower: maxPower,
usedPower: 0,
endTimestamp: endTimestamp
});
// Add the Proxy to the user's list
currentUserProxyVoters[user].push(proxy);
emit SetNewProxyVoter(user, proxy, maxPower, endTimestamp);
}
/**
* @notice Clears expired Proxies for a user
* @dev Clears all expired Proxies for a user & frees the blocked voting power
* @param user Address of the user
*/functionclearUserExpiredProxies(address user) external{
_clearExpiredProxies(user);
}
// Internal functions/**
* @dev Checks if a gauge is listed
* @param gauge Address of the gauge
* @return bool : Is the gauge listed
*/function_isGaugeListed(address gauge) internalviewreturns(bool) {
return gaugeToBoardId[gauge] !=0;
}
/**
* @dev Clears expired Proxies for a user & frees the blocked voting power
* @param user Address of the user
*/function_clearExpiredProxies(address user) internal{
uint256 length = currentUserProxyVoters[user].length;
if(length ==0) return;
for(uint256 i; i < length;) {
address proxyVoter = currentUserProxyVoters[user][i];
if(proxyVoterState[user][proxyVoter].endTimestamp <block.timestamp) {
// Free the user blocked voting power
blockedProxyPower[user] -= proxyVoterState[user][proxyVoter].maxPower;
// Delete the Proxydelete proxyVoterState[user][proxyVoter];
// Remove the Proxy from the user's listuint256 lastIndex = length -1;
if(i != lastIndex) {
currentUserProxyVoters[user][i] = currentUserProxyVoters[user][length-1];
}
currentUserProxyVoters[user].pop();
length--;
} else {
unchecked{ i++; }
}
}
}
/**
* @dev Vote for a gauge weight based on the given user power
* @param user Address of the user
* @param gauge Address of the gauge
* @param userPower Power used for this gauge
* @param caller Address of the caller
*/function_voteForGauge(address user, address gauge, uint256 userPower, address caller) internal{
VoteVars memory vars;
// Get the periods timestamps & user lock state
vars.currentPeriod = (block.timestamp) / WEEK * WEEK;
vars.nextPeriod = vars.currentPeriod + WEEK;
vars.userSlope = IHolyPalPower(hPalPower).getUserPoint(user).slope;
vars.userLockEnd = IHolyPalPower(hPalPower).locked__end(user);
// Check the gauge is listed & the user lock is not expiredif(!_isGaugeListed(gauge)) revert Errors.NotListed();
if(vars.userLockEnd <= vars.nextPeriod) revert Errors.LockExpired();
// Check the user has enough voting power & the cooldown is respectedif(userPower > MAX_BPS) revert Errors.VotingPowerInvalid();
if(block.timestamp< lastUserVote[user][gauge] + VOTE_COOLDOWN) revert Errors.VotingCooldown();
// Load the user past vote state
VotedSlope memory oldSlope = voteUserSlopes[user][gauge];
if(oldSlope.end > vars.nextPeriod) {
vars.oldBias = oldSlope.slope * (oldSlope.end - vars.nextPeriod);
}
// No vote to cast & no previous vote to remove == useless actionif(userPower ==0&& oldSlope.power ==0) return;
// Calculate the new vote state
VotedSlope memory newSlope = VotedSlope({
slope: (convertInt128ToUint128(vars.userSlope) * userPower) / MAX_BPS,
power: userPower,
end: vars.userLockEnd,
caller: caller
});
vars.newBias = newSlope.slope * (vars.userLockEnd - vars.nextPeriod);
// Check if the caller is allowed to change this voteif(
oldSlope.caller != caller && proxyVoterState[user][oldSlope.caller].endTimestamp >block.timestamp
) revert Errors.NotAllowedVoteChange();
// Update the voter used voting power & the proxy one if needed
vars.totalPowerUsed = voteUserPower[user];
vars.totalPowerUsed = vars.totalPowerUsed + newSlope.power - oldSlope.power;
if(user == caller) {
uint256 usedPower = usedFreePower[user];
vars.oldUsedPower = oldSlope.caller != user ? 0 : oldSlope.power;
usedPower = usedPower + newSlope.power - vars.oldUsedPower;
if(usedPower > (MAX_BPS - blockedProxyPower[user])) revert Errors.VotingPowerExceeded();
usedFreePower[user] = usedPower;
} else {
uint256 proxyPower = proxyVoterState[user][caller].usedPower;
vars.oldUsedPower = oldSlope.caller == caller ? oldSlope.power : 0;
proxyPower = proxyPower + newSlope.power - vars.oldUsedPower;
if(oldSlope.caller == user) {
usedFreePower[user] -= oldSlope.power;
}
if(proxyPower > proxyVoterState[user][caller].maxPower) revert Errors.VotingPowerProxyExceeded();
proxyVoterState[user][caller].usedPower = proxyPower;
}
if(vars.totalPowerUsed > MAX_BPS) revert Errors.VotingPowerExceeded();
voteUserPower[user] = vars.totalPowerUsed;
// Update the gauge weight
vars.oldWeightBias = _updateGaugeWeight(gauge);
vars.oldWeightSlope = pointsWeight[gauge][vars.nextPeriod].slope;
// Update the total weight
vars.oldTotalBias = _updateTotalWeight();
vars.oldTotalSlope = pointsWeightTotal[vars.nextPeriod].slope;
// Update the new gauge bias & total bias
pointsWeight[gauge][vars.nextPeriod].bias = max(vars.oldWeightBias + vars.newBias, vars.oldBias) - vars.oldBias;
pointsWeightTotal[vars.nextPeriod].bias = max(vars.oldTotalBias + vars.newBias, vars.oldBias) - vars.oldBias;
// Update the new gauge slope & total slopeif(oldSlope.end > vars.nextPeriod) {
pointsWeight[gauge][vars.nextPeriod].slope = max(vars.oldWeightSlope + newSlope.slope, oldSlope.slope) - oldSlope.slope;
pointsWeightTotal[vars.nextPeriod].slope = max(vars.oldTotalSlope + newSlope.slope, oldSlope.slope) - oldSlope.slope;
} else {
pointsWeight[gauge][vars.nextPeriod].slope += newSlope.slope;
pointsWeightTotal[vars.nextPeriod].slope += newSlope.slope;
}
// Update the gauge slope changes & total slope changesif(oldSlope.end >block.timestamp) {
changesWeight[gauge][oldSlope.end] -= oldSlope.slope;
changesWeightTotal[oldSlope.end] -= oldSlope.slope;
}
changesWeight[gauge][newSlope.end] += newSlope.slope;
changesWeightTotal[newSlope.end] += newSlope.slope;
// Store the user vote state
voteUserSlopes[user][gauge] = newSlope;
lastUserVote[user][gauge] =block.timestamp;
emit VoteForGauge(block.timestamp, user, gauge, userPower);
}
/**
* @dev Returns a gauge relative weight based on its weight and the total weight at a given period
* @param gauge Address of the gauge
* @param ts Timestamp
* @return uint256 : Gauge relative weight
*/function_getGaugeRelativeWeight(address gauge, uint256 ts) internalviewreturns(uint256) {
if(isGaugeKilled[gauge]) return0;
ts = ts / WEEK * WEEK;
uint256 _totalWeight = pointsWeightTotal[ts].bias;
if(_totalWeight ==0) return0;
return (pointsWeight[gauge][ts].bias * UNIT) / _totalWeight;
}
/**
* @dev Updates the gauge weight for all past non-updated periods & returns the current gauge weight
* @param gauge Address of the gauge
* @return uint256 : Current gauge weight
*/function_updateGaugeWeight(address gauge) internalreturns(uint256) {
uint256 ts = timeWeight[gauge];
if(ts ==0) return0;
Point memory _point = pointsWeight[gauge][ts];
for(uint256 i; i <500; i++) {
if(ts >block.timestamp) break;
ts += WEEK;
uint256 decreaseBias = _point.slope * WEEK;
if(decreaseBias >= _point.bias) {
_point.bias =0;
_point.slope =0;
} else {
_point.bias -= decreaseBias;
uint256 decreaseSlope = changesWeight[gauge][ts];
_point.slope -= decreaseSlope;
}
pointsWeight[gauge][ts] = _point;
if(ts >block.timestamp) {
timeWeight[gauge] = ts;
}
}
return _point.bias;
}
/**
* @dev Updates the total weight for all past non-updated periods & returns the current total weight
* @return uint256 : Current total weight
*/function_updateTotalWeight() internalreturns(uint256) {
uint256 ts = timeTotal;
if(ts ==0) return0;
Point memory _point = pointsWeightTotal[ts];
for(uint256 i; i <500; i++) {
if(ts >block.timestamp) break;
ts += WEEK;
uint256 decreaseBias = _point.slope * WEEK;
if(decreaseBias >= _point.bias) {
_point.bias =0;
_point.slope =0;
} else {
_point.bias -= decreaseBias;
uint256 decreaseSlope = changesWeightTotal[ts];
_point.slope -= decreaseSlope;
}
pointsWeightTotal[ts] = _point;
if(ts >block.timestamp) {
timeTotal = ts;
}
}
return _point.bias;
}
// Admin functions/**
* @notice Adds a new Quest Board & its Distributor
* @dev Adds a new Quest Board & its Distributor
* @param board Address of the Quest Board
* @param distributor Address of the Distributor
*/functionaddNewBoard(address board, address distributor) externalonlyOwner{
if(board ==address(0) || distributor ==address(0)) revert Errors.AddressZero();
if(boardToId[board] !=0|| distributorToId[distributor] !=0) revert Errors.AlreadyListed();
uint256 boardId = nextBoardId;
nextBoardId++;
questBoards[boardId] = QuestBoard(board, distributor);
boardToId[board] = boardId;
distributorToId[distributor] = boardId;
emit NewBoardListed(boardId, board, distributor);
}
/**
* @notice Updates the Distributor for a Quest Board
* @dev Updates the Distributor for a Quest Board
* @param board Address of the Quest Board
* @param newDistributor Address of the new Distributor
*/functionupdateDistributor(address board, address newDistributor) externalonlyOwner{
if(board ==address(0) || newDistributor ==address(0)) revert Errors.AddressZero();
if(distributorToId[newDistributor] !=0) revert Errors.AlreadyListed();
uint256 boardId = boardToId[board];
if(boardId ==0) revert Errors.InvalidParameter();
questBoards[boardId].distributor = newDistributor;
distributorToId[newDistributor] = boardId;
emit BoardUpdated(boardId, newDistributor);
}
/**
* @notice Adds a new Gauge (with a cap)
* @dev Adds a new Gauge linked to a listed Quest Board & sets a weight cap
* @param gauge Address of the gauge
* @param boardId ID of the Quest Board
* @param cap Weight cap for the gauge
*/functionaddNewGauge(address gauge, uint256 boardId, uint256 cap) externalonlyOwner{
if(gauge ==address(0)) revert Errors.AddressZero();
if(boardId ==0) revert Errors.InvalidParameter();
if(_isGaugeListed(gauge)) revert Errors.AlreadyListed();
if((cap < MIN_GAUGE_CAP && cap !=0) || cap > MAX_GAUGE_CAP) revert Errors.InvalidGaugeCap();
gaugeToBoardId[gauge] = boardId;
gaugeCaps[gauge] = cap;
timeWeight[gauge] = (block.timestamp+ WEEK) / WEEK * WEEK;
emit NewGaugeAdded(gauge, boardId, cap);
}
/**
* @notice Updates the Board ID for a gauge
* @dev Updates the Board ID for a gauge
* @param gauge Address of the gauge
* @param newBoardId New Board ID for the gauge
*/functionupdateGaugeBoard(address gauge, uint256 newBoardId) externalonlyOwner{
if(gauge ==address(0)) revert Errors.AddressZero();
if(gaugeToBoardId[gauge] ==0) revert Errors.InvalidParameter();
if(isGaugeKilled[gauge]) revert Errors.KilledGauge();
gaugeToBoardId[gauge] = newBoardId;
emit GaugeBoardUpdated(gauge, newBoardId);
}
/**
* @notice Updates the weight cap for a gauge
* @dev Updates the weight cap for a gauge
* @param gauge Address of the gauge
* @param newCap New weight cap for the gauge
*/functionupdateGaugeCap(address gauge, uint256 newCap) externalonlyOwner{
if(gauge ==address(0)) revert Errors.AddressZero();
if(gaugeToBoardId[gauge] ==0) revert Errors.InvalidParameter();
if(isGaugeKilled[gauge]) revert Errors.KilledGauge();
if((newCap < MIN_GAUGE_CAP && newCap !=0) || newCap > MAX_GAUGE_CAP) revert Errors.InvalidGaugeCap();
gaugeCaps[gauge] = newCap;
emit GaugeCapUpdated(gauge, gaugeToBoardId[gauge], newCap);
}
/**
* @notice Updates the default weight cap
* @dev Updates the default weight cap
* @param newCap New default weight cap
*/functionupdateDefaultGaugeCap(uint256 newCap) externalonlyOwner{
if(newCap < MIN_GAUGE_CAP || newCap > MAX_GAUGE_CAP) revert Errors.InvalidGaugeCap();
defaultCap = newCap;
emit DefaultCapUpdated(newCap);
}
/**
* @notice Kills a gauge
* @dev Kills a gauge, blocking the votes & weight updates
* @param gauge Address of the gauge
*/functionkillGauge(address gauge) externalonlyOwner{
if(gauge ==address(0)) revert Errors.AddressZero();
if(!_isGaugeListed(gauge)) revert Errors.NotListed();
if(isGaugeKilled[gauge]) revert Errors.KilledGauge();
isGaugeKilled[gauge] =true;
emit GaugeKilled(gauge, gaugeToBoardId[gauge]);
}
/**
* @notice Unkills a gauge
* @dev Unkills a gauge, unblocking the votes & weight updates
* @param gauge Address of the gauge
*/functionunkillGauge(address gauge) externalonlyOwner{
if(gauge ==address(0)) revert Errors.AddressZero();
if(!isGaugeKilled[gauge]) revert Errors.NotKilledGauge();
isGaugeKilled[gauge] =false;
emit GaugeUnkilled(gauge, gaugeToBoardId[gauge]);
}
// MathsfunctionconvertInt128ToUint128(int128 value) internalpurereturns(uint128) {
if (value <0) revert Errors.ConversionOverflow();
returnuint128(value);
}
functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
}
Contract Source Code
File 9 of 11: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)pragmasolidity ^0.8.20;import {Context} from"../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.
*
* The initial owner is set to the address provided by the deployer. 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;
/**
* @dev The caller account is not authorized to perform an operation.
*/errorOwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/errorOwnableInvalidOwner(address owner);
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/constructor(address initialOwner) {
if (initialOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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{
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling 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{
if (newOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.20;import {IERC20} from"../IERC20.sol";
import {IERC20Permit} from"../extensions/IERC20Permit.sol";
import {Address} from"../../../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;
/**
* @dev An operation with an ERC20 token failed.
*/errorSafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/errorSafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal{
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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);
if (returndata.length!=0&&!abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// 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 cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return success && (returndata.length==0||abi.decode(returndata, (bool))) &&address(token).code.length>0;
}
}