// 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 7: IERC1363.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1363.sol)pragmasolidity ^0.8.20;import {IERC20} from"./IERC20.sol";
import {IERC165} from"./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/interfaceIERC1363isIERC20, IERC165{
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*//**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functiontransferAndCall(address to, uint256 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functiontransferAndCall(address to, uint256 value, bytescalldata data) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functiontransferFromAndCall(addressfrom, address to, uint256 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functiontransferFromAndCall(addressfrom, address to, uint256 value, bytescalldata data) externalreturns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functionapproveAndCall(address spender, uint256 value) externalreturns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/functionapproveAndCall(address spender, uint256 value, bytescalldata data) externalreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/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);
}
pragmasolidity >=0.8.0;import"./interfaces/INXDProtocol.sol";
import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
contractNXDStakingVault{
usingSafeERC20forIERC20;
errorPoolAlreadyAdded();
errorInvalidAmount();
errorSendETHFail();
errorNoRequest();
errorCooldown();
errorUnderflow();
errorLocked();
errorWithdrawDisabled();
eventAdd(addressindexed token, uint256indexed pid, uint256 allocPoint, bool withdrawable);
eventDeposit(addressindexed user, uint256indexed pid, uint256 amount);
eventWithdraw(addressindexed user, uint256indexed pid, uint256 amount);
eventEmergencyWithdraw(addressindexed user, uint256indexed pid, uint256 amount);
eventApproval(addressindexed owner, addressindexed spender, uint256 _pid, uint256 value);
eventWithdrawRequested(addressindexed user, uint256 amount, uint256 canWithdrawAfterTimestamp);
// Info of each user.structUserInfo {
uint256 amount; // How many tokens the user has provided.uint256 rewardDebt; // Reward debt. See explanation below.//// We do some fancy math here. Basically, any point in time, the amount of ETHs// entitled to a user but is pending to be distributed is://// pending reward = (user.amount * pool.accEthPerShare) - user.rewardDebt//// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:// 1. The pool's `accEthPerShare` (and `lastRewardBlock`) gets updated.// 2. User receives the pending reward sent to his/her address.// 3. User's `amount` gets updated.// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.structPoolInfo {
IERC20 token; // Address of token contract.uint256 allocPoint; // How many allocation points assigned to this pool. ETHs to distribute per block.uint256 accEthPerShare; // Accumulated ETHs per share, times 1e12. See below.bool withdrawable; // Is this pool withdrawable?
}
// Info of each pool.uint256public numPools;
mapping(uint256=> PoolInfo) public poolInfo;
mapping(uint256=>mapping(address=> UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.uint256public totalAllocPoint;
// pid => owner => timestamp// mapping(uint256 => mapping(address => uint256)) public canWithdrawAfter;structWithdrawalRequest {
uint256 amount;
uint256 canWithdrawAfterTimestamp;
}
// pid => owner => WithdrawalRequestmapping(uint256=>mapping(address=> WithdrawalRequest)) public withdrawalRequests;
uint256publicconstant WITHDRAWAL_COOLDOWN =1days;
//// pending rewards awaiting anyone to massUpdateuint256public pendingRewards;
// The NXD TOKEN!
IERC20 publicimmutable nxd;
INXDProtocol publicimmutable nxdProtocol;
// keep track of latest known eth balance. used to determine new rewardsuint256public ourETHBalance;
boolpublic locked;
uint256public nxdPenaltyBurned;
uint256public totalStaked;
// variables used to calculate rewards apyuint256public contractStartBlock;
uint256public epochCalculationStartBlock;
uint256public cumulativeRewardsSinceStart;
uint256public rewardsInThisEpoch;
uint256public epoch;
// Returns fees generated since start of this contractfunctionaverageFeesPerBlockSinceStart() externalviewreturns (uint256 averagePerBlock) {
averagePerBlock = (cumulativeRewardsSinceStart + rewardsInThisEpoch) / (block.number- (contractStartBlock));
}
// Returns averge fees in this epochfunctionaverageFeesPerBlockEpoch() externalviewreturns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch / (block.number- epochCalculationStartBlock);
}
// For easy graphing historical epoch rewardsmapping(uint256=>uint256) public epochRewards;
//Starts a new calculation epoch// Because averge since start will not be accuratefunctionstartNewEpochIfReady() public{
if (epochCalculationStartBlock +50000<block.number) {
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart += rewardsInThisEpoch;
rewardsInThisEpoch =0;
epochCalculationStartBlock =block.number;
++epoch;
}
}
// Reentrancy lockmodifierlock() {
if (locked) {
revert Locked();
}
locked =true;
_;
locked =false;
}
constructor(IERC20 _nxd) {
nxd = _nxd;
nxdProtocol = INXDProtocol(msg.sender);
_add(100, _nxd, false, true);
contractStartBlock =block.number;
startNewEpochIfReady();
}
// Add a new token pool. Can only be when contract is deployed.function_add(uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable) internal{
if (_withUpdate) {
massUpdatePools();
}
uint256 length = numPools;
for (uint256 pid =0; pid < length; ++pid) {
if (poolInfo[pid].token == _token) {
revert PoolAlreadyAdded();
}
}
totalAllocPoint = totalAllocPoint + _allocPoint;
PoolInfo storage _poolInfo = poolInfo[length];
_poolInfo.token = _token;
_poolInfo.allocPoint = _allocPoint;
_poolInfo.accEthPerShare =0;
_poolInfo.withdrawable = _withdrawable;
numPools +=1;
emit Add(address(_token), length, _allocPoint, _withdrawable);
}
// View function to see pending ETHs on frontend.functionpendingETH(uint256 _pid, address _user) publicviewreturns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEthPerShare = pool.accEthPerShare;
return ((user.amount * accEthPerShare) /1e12) - user.rewardDebt;
}
// Update reward vairables for all pools. Be careful of gas spending!functionmassUpdatePools() public{
uint256 length = numPools;
uint256 allRewards;
for (uint256 pid =0; pid < length; ++pid) {
allRewards = allRewards + updatePool(pid);
}
pendingRewards = pendingRewards - allRewards;
}
functionaddPendingRewards() public{
startNewEpochIfReady();
uint256 newRewards =address(this).balance- ourETHBalance;
if (newRewards >0) {
ourETHBalance =address(this).balance; // If there is no change the balance didn't change
pendingRewards = pendingRewards + newRewards;
rewardsInThisEpoch += newRewards;
}
}
// Update reward variables of the given pool to be up-to-date.functionupdatePool(uint256 _pid) internalreturns (uint256 ethReward) {
PoolInfo storage pool = poolInfo[_pid];
if (totalStaked ==0) {
// avoids division by 0 errorsreturn0;
}
ethReward = (pendingRewards * pool.allocPoint) // Multiplies pending rewards by allocation point of this pool and then total allocation// getting the percent of total pending rewards this pool should get/ totalAllocPoint; // we can do this because pools are only mass updated
pool.accEthPerShare += ((ethReward *1e12) / totalStaked);
}
// Deposit NXD tokens to NXDStakingVault for ETH allocation.functiondeposit(uint256 _pid, uint256 _amount) publiclock{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user// save gasif (_amount >0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount += _amount;
totalStaked += _amount;
}
user.rewardDebt = (user.amount * pool.accEthPerShare) /1e12;
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage// [x] Does user get the deposited amounts?// [x] Does user that its deposited for update correcty?// [x] Does the depositor get their tokens decreasedfunctiondepositFor(address _depositFor, uint256 _pid, uint256 _amount) publiclock{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositFor];
massUpdatePools();
// Transfer pending tokens// to user
updateAndPayOutPending(_pid, _depositFor); // Update the balances of person that amount is being deposited forif (_amount >0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount += _amount; // This is depositedFor address
totalStaked += _amount;
}
user.rewardDebt = (user.amount * pool.accEthPerShare) /1e12;
/// This is deposited for addressemit Deposit(_depositFor, _pid, _amount);
}
// Withdraw tokens from NXDStakingVault.functionwithdraw(uint256 _pid, uint256 _amount, bool acceptsPenalty) publiclock{
_withdraw(_pid, _amount, msg.sender, msg.sender, acceptsPenalty);
}
// Low level withdraw functionfunction_withdraw(uint256 _pid, uint256 _amount, addressfrom, address to, bool acceptsPenalty) internal{
PoolInfo storage pool = poolInfo[_pid];
if (!pool.withdrawable) {
revert WithdrawDisabled();
}
UserInfo storage user = userInfo[_pid][from];
if (user.amount < _amount) {
revert Underflow();
}
uint256 userGetsAfterPenalty = _amount;
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from. This is not withdrawal but claiming ETH farmed
WithdrawalRequest storage request = withdrawalRequests[_pid][msg.sender];
if (_amount >0) {
if (block.timestamp>= request.canWithdrawAfterTimestamp && request.canWithdrawAfterTimestamp !=0) {
withdrawCooldown(_pid);
}
// Stop receiving rewards for this amount NOW
user.amount = user.amount - _amount;
totalStaked -= _amount;
if (acceptsPenalty) {
userGetsAfterPenalty = (_amount *7500) /10000;
} else {
// 0 means Needs to wait 24 hoursif (request.canWithdrawAfterTimestamp ==0) {
uint256 timestamp =block.timestamp+ WITHDRAWAL_COOLDOWN;
withdrawalRequests[_pid][msg.sender] = WithdrawalRequest(_amount, timestamp);
user.rewardDebt = (user.amount * pool.accEthPerShare) /1e12;
emit WithdrawRequested(from, _amount, timestamp);
return;
} else {
revert Cooldown();
}
}
// If we are here we can withdraw
pool.token.safeTransfer(address(to), userGetsAfterPenalty);
// Burn penalty amountif (userGetsAfterPenalty < _amount) {
uint256 amountToBurn = _amount - userGetsAfterPenalty;
nxd.transfer(0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF, amountToBurn);
nxdPenaltyBurned += amountToBurn;
}
}
user.rewardDebt = (user.amount * pool.accEthPerShare) /1e12;
emit Withdraw(to, _pid, _amount);
}
/**
* @notice Withdraws the amount requested if the cooldown period has passed. If the user has not requested a withdrawal or the cooldown period has not passed, the function reverts.
* @param _pid The pool id.
*/functionwithdrawCooldown(uint256 _pid) public{
PoolInfo storage pool = poolInfo[_pid];
WithdrawalRequest storage request = withdrawalRequests[_pid][msg.sender];
if (request.canWithdrawAfterTimestamp ==0|| request.amount ==0) {
revert NoRequest();
}
if (block.timestamp< request.canWithdrawAfterTimestamp) {
revert Cooldown();
}
uint256 amount = request.amount;
request.canWithdrawAfterTimestamp =0;
request.amount =0;
pool.token.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, _pid, request.amount);
}
functionupdateAndPayOutPending(uint256 _pid, addressfrom) internal{
uint256 pending = pendingETH(_pid, from);
if (pending >0) {
safeETHTransfer(from, pending);
}
nxdProtocol.collectFees();
nxdProtocol.stakeOurDXN();
}
// Withdraw without caring about rewards. EMERGENCY ONLY.// !Caution this will remove all your pending rewards!functionemergencyWithdraw(uint256 _pid) publiclock{
PoolInfo storage pool = poolInfo[_pid];
if (!pool.withdrawable) {
revert WithdrawDisabled();
}
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount =0;
user.rewardDebt =0;
// No mass update dont update pending rewards
}
// Safe eth transfer functionfunctionsafeETHTransfer(address _to, uint256 _amount) internal{
(bool sent,) = _to.call{value: _amount}("");
if (!sent) {
revert SendETHFail();
}
ourETHBalance =address(this).balance;
//Avoids possible recursion loop// proxy?
}
/**
* @dev Receives ETH from NXDProtocol and updates pending rewards.
*/receive() externalpayable{
addPendingRewards();
}
}
Contract Source Code
File 7 of 7: SafeERC20.sol
// 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 {IERC1363} from"../../../interfaces/IERC1363.sol";
import {Address} from"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 ERC-20 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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/functiontransferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytesmemory data) internal{
if (to.code.length==0) {
safeTransfer(token, to, value);
} elseif (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/functiontransferFromAndCallRelaxed(
IERC1363 token,
addressfrom,
address to,
uint256 value,
bytesmemory data
) internal{
if (to.code.length==0) {
safeTransferFrom(token, from, to, value);
} elseif (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/functionapproveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytesmemory data) internal{
if (to.code.length==0) {
forceApprove(token, to, value);
} elseif (!token.approveAndCall(to, value, data)) {
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).
*/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;
}
}