Transaction Hash:
Block:
24181706 at Jan-07-2026 08:48:23 AM +UTC
Transaction Fee:
0.000007394221093152 ETH
$0.01
Gas Used:
188,112 Gas / 0.039307546 Gwei
Emitted Events:
| 688 |
TetherToken.Transfer( from=[Sender] 0x1a95cac98131221ad3a5ca1eca9270b004d1f503, to=0x000010036C0190E009a000d0fc3541100A07380A, value=1004171000 )
|
| 689 |
TetherToken.Transfer( from=0x000010036C0190E009a000d0fc3541100A07380A, to=CreditVault, value=1004171000 )
|
| 690 |
WETH9.Transfer( src=CreditVault, dst=[Receiver] AugustusV6, wad=308565356358242285 )
|
| 691 |
0xc419e67388df0c0cfad15584fc5fc7e67a234c17.0xc82975a4eae9f14416813a0bd7312edf547928cd25ae9b8597ee4c92fa6862d2( 0xc82975a4eae9f14416813a0bd7312edf547928cd25ae9b8597ee4c92fa6862d2, 0000000000000000000000006a000f20005980200259b80c5102003040001068, 000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7, 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2, 000000000000000000000000000000000000000000000000000000003bda6ef8, 00000000000000000000000000000000000000000000000004483e8e87b98fed, a46be512a4ba41deae2419bc3558d6c700000000000000000000000000000000, 000000000000000000000000129b3d9a0a6e4beab88f5cb1e57995d72a6e24f1 )
|
| 692 |
WETH9.Transfer( src=[Receiver] AugustusV6, dst=[Sender] 0x1a95cac98131221ad3a5ca1eca9270b004d1f503, wad=308565356358242285 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x1A95CAC9...004d1F503 |
0.009769278547276982 Eth
Nonce: 48
|
0.00976188432618383 Eth
Nonce: 49
| 0.000007394221093152 | ||
| 0xC02aaA39...83C756Cc2 | |||||
| 0xc419e673...67a234c17 | |||||
| 0xdAC17F95...13D831ec7 | |||||
| 0xe3D41d19...030f5f2EF |
Execution Trace
AugustusV6.swapExactAmountIn( executor=0x000010036C0190E009a000d0fc3541100A07380A, swapData=[{name:srcToken, type:address, order:1, indexed:false, value:0xdAC17F958D2ee523a2206206994597C13D831ec7, valueString:0xdAC17F958D2ee523a2206206994597C13D831ec7}, {name:destToken, type:address, order:2, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:fromAmount, type:uint256, order:3, indexed:false, value:1004171000, valueString:1004171000}, {name:toAmount, type:uint256, order:4, indexed:false, value:305527248876401352, valueString:305527248876401352}, {name:quotedAmount, type:uint256, order:5, indexed:false, value:308613382703435710, valueString:308613382703435710}, {name:metadata, type:bytes32, order:6, indexed:false, value:740FBEE9BCB44E17ACFE7F0F8A0A408B0000000000000000000000000170FBC8, valueString:740FBEE9BCB44E17ACFE7F0F8A0A408B0000000000000000000000000170FBC8}, {name:beneficiary, type:address, order:7, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}], partnerAndFee=4951760157141521099596496896, permit=0x, executorData=0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004608A2DDC0461FCF96F81A05529BED540D4F1EB2A000000040000240000FF000003000000000000000000000000000000000000000000000000000000000947C2D9000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C419E67388DF0C0CFAD15584FC5FC7E67A234C17000000000000000000000000129B3D9A0A6E4BEAB88F5CB1E57995D72A6E24F10000000000000000000000006A000F20005980200259B80C5102003040001068000000000000000000000000DAC17F958D2EE523A2206206994597C13D831EC7000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000000000000000000000000000000000003BDA6EF800000000000000000000000000000000000000000000000004485A9F9882130E000000000000000000000000000000000000000000000000044741F4F0ACF3CD00000000000000000000000000000000000000000000000000000000695E1E0500000000000000000000000000000000000000000000000049CFFE267036586700000000000000000000000000000000000000000000000000000000695E1DD200000000000000000000000000000000000000000000000000000000695E1DF00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000AA46BE512A4BA41DEAE2419BC3558D6C700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002800000000000000000000000006044EEF7179034319E2C8636EA885B37CBFA9ABA000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000041EE9056CD1B8C81850DAA7768173BF4215BDF85A306AE7720348264815ACE9EC40277B92220298CF1F6A999748004A5F9DFA250BC6E9235E0D40762748F47074B1B000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041D67154E1A07E684CE5B245FD7DFAD29F32369433930521E9EDFD09C266A6634A307062BAC5A75A72A830EA278722437633EEB96E495E0F43136882AA67A8E7361B00000000000000000000000000000000000000000000000000000000000000 ) => ( receivedAmount=308565356358242285, paraswapShare=0, partnerShare=0 )
-
TetherToken.transferFrom( _from=0x1A95CAC98131221aD3a5cA1eCA9270b004d1F503, _to=0x000010036C0190E009a000d0fc3541100A07380A, _value=1004171000 )
0x000010036c0190e009a000d0fc3541100a07380a.00000000( )0x8a2ddc0461fcf96f81a05529bed540d4f1eb2a00.0947c2d9( )-
Null: 0x000...001.6a563844( ) -
0xc419e67388df0c0cfad15584fc5fc7e67a234c17.STATICCALL( ) -
TetherToken.transferFrom( _from=0x000010036C0190E009a000d0fc3541100A07380A, _to=0xe3D41d19564922C9952f692C5Dd0563030f5f2EF, _value=1004171000 )
0xc419e67388df0c0cfad15584fc5fc7e67a234c17.aae6dd92( )-
Null: 0x000...001.dc3a5994( ) -
CreditVault.swapCallback( trader=0x129b3d9a0A6e4Beab88F5CB1e57995d72a6e24f1, tokenIn=0xdAC17F958D2ee523a2206206994597C13D831ec7, amountIn=1004171000, tokenOut=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, amountOut=308565356358242285 ) -
WETH9.transferFrom( src=0xe3D41d19564922C9952f692C5Dd0563030f5f2EF, dst=0x6A000F20005980200259B80c5102003040001068, wad=308565356358242285 ) => ( True )
-
-
-
WETH9.balanceOf( 0x6A000F20005980200259B80c5102003040001068 ) => ( 308565356358242286 )
-
WETH9.transfer( dst=0x1A95CAC98131221aD3a5cA1eCA9270b004d1F503, wad=308565356358242285 ) => ( True )
File 1 of 4: AugustusV6
File 2 of 4: TetherToken
File 3 of 4: CreditVault
File 4 of 4: WETH9
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Vendor
import { Diamond } from "./vendor/Diamond.sol";
// Routers
import { Routers } from "./routers/Routers.sol";
// ______ __ __ __ ____
// /\\ _ \\ /\\ \\__ /\\ \\/\\ \\ /'___\\
// \\ \\ \\L\\ \\ __ __ __ __ __ ____\\ \\ ,_\\ __ __ ____\\ \\ \\ \\ \\/\\ \\__/
// \\ \\ __ \\/\\ \\/\\ \\ /'_ `\\/\\ \\/\\ \\ /',__\\\\ \\ \\/ /\\ \\/\\ \\ /',__\\\\ \\ \\ \\ \\ \\ _``\\
// \\ \\ \\/\\ \\ \\ \\_\\ \\/\\ \\L\\ \\ \\ \\_\\ \\/\\__, `\\\\ \\ \\_\\ \\ \\_\\ \\/\\__, `\\\\ \\ \\_/ \\ \\ \\L\\ \\
// \\ \\_\\ \\_\\ \\____/\\ \\____ \\ \\____/\\/\\____/ \\ \\__\\\\ \\____/\\/\\____/ \\ `\\___/\\ \\____/
// \\/_/\\/_/\\/___/ \\/___L\\ \\/___/ \\/___/ \\/__/ \\/___/ \\/___/ `\\/__/ \\/___/
// /\\____/
// \\_/__/
/// @title AugustusV6
/// @notice The V6 implementation of the ParaSwap onchain aggregation protocol
contract AugustusV6 is Diamond, Routers {
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
/// @dev Diamond
address _owner,
address _diamondCutFacet,
/// @dev Direct Routers
address _weth,
address payable _balancerVault,
uint256 _uniV3FactoryAndFF,
uint256 _uniswapV3PoolInitCodeHash,
uint256 _uniswapV2FactoryAndFF,
uint256 _uniswapV2PoolInitCodeHash,
address _rfq,
/// @dev Fees
address payable _feeVault,
/// @dev Permit2
address _permit2
)
Diamond(_owner, _diamondCutFacet)
Routers(
_weth,
_uniV3FactoryAndFF,
_uniswapV3PoolInitCodeHash,
_uniswapV2FactoryAndFF,
_uniswapV2PoolInitCodeHash,
_balancerVault,
_permit2,
_rfq,
_feeVault
)
{ }
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
/// @notice Reverts if the caller is one of the following:
// - 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
receive() external payable override(Diamond) {
address addr = msg.sender;
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
if iszero(extcodesize(addr)) { revert(0, 0) }
}
}
}
// SPDX-License-Identifier: MIT
/**
* Vendored on October 12, 2023 from:
* https://github.com/mudgen/diamond-3-hardhat/blob/main/contracts/Diamond.sol
*/
pragma solidity ^0.8.0;
/**
* \\
* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
*
* Implementation of a diamond.
* /*****************************************************************************
*/
import { LibDiamond } from "./libraries/LibDiamond.sol";
import { IDiamondCut } from "./interfaces/IDiamondCut.sol";
contract Diamond {
error DiamondFunctionDoesNotExist();
constructor(address _contractOwner, address _diamondCutFacet) payable {
LibDiamond.setContractOwner(_contractOwner);
// Add the diamondCut external function from the diamondCutFacet
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({
facetAddress: _diamondCutFacet,
action: IDiamondCut.FacetCutAction.Add,
functionSelectors: functionSelectors
});
LibDiamond.diamondCut(cut, address(0), "");
}
// Find facet for function that is called and execute the
// function if a facet is found and return any value.
fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
// get diamond storage
assembly {
ds.slot := position
}
// get facet from function selector
address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress;
// revert if function does not exist
if (facet == address(0)) {
revert DiamondFunctionDoesNotExist();
}
// Execute external function from facet using delegatecall and return any value.
assembly {
// copy function selector and any arguments
calldatacopy(0, 0, calldatasize())
// execute function call using the facet
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
// get any return value
returndatacopy(0, 0, returndatasize())
// return any return value or error back to the caller
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
receive() external payable virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// DirectSwapExactAmountIn
import { BalancerV2SwapExactAmountIn } from "./swapExactAmountIn/direct/BalancerV2SwapExactAmountIn.sol";
import { CurveV1SwapExactAmountIn } from "./swapExactAmountIn/direct/CurveV1SwapExactAmountIn.sol";
import { CurveV2SwapExactAmountIn } from "./swapExactAmountIn/direct/CurveV2SwapExactAmountIn.sol";
import { UniswapV2SwapExactAmountIn } from "./swapExactAmountIn/direct/UniswapV2SwapExactAmountIn.sol";
import { UniswapV3SwapExactAmountIn } from "./swapExactAmountIn/direct/UniswapV3SwapExactAmountIn.sol";
// DirectSwapExactAmountOut
import { BalancerV2SwapExactAmountOut } from "./swapExactAmountOut/direct/BalancerV2SwapExactAmountOut.sol";
import { UniswapV2SwapExactAmountOut } from "./swapExactAmountOut/direct/UniswapV2SwapExactAmountOut.sol";
import { UniswapV3SwapExactAmountOut } from "./swapExactAmountOut/direct/UniswapV3SwapExactAmountOut.sol";
// Fees
import { AugustusFees } from "../fees/AugustusFees.sol";
// GenericSwapExactAmountIn
import { GenericSwapExactAmountIn } from "./swapExactAmountIn/GenericSwapExactAmountIn.sol";
// GenericSwapExactAmountOut
import { GenericSwapExactAmountOut } from "./swapExactAmountOut/GenericSwapExactAmountOut.sol";
// General
import { AugustusRFQRouter } from "./general/AugustusRFQRouter.sol";
// Utils
import { AugustusRFQUtils } from "../util/AugustusRFQUtils.sol";
import { BalancerV2Utils } from "../util/BalancerV2Utils.sol";
import { UniswapV2Utils } from "../util/UniswapV2Utils.sol";
import { UniswapV3Utils } from "../util/UniswapV3Utils.sol";
import { WETHUtils } from "../util/WETHUtils.sol";
import { Permit2Utils } from "../util/Permit2Utils.sol";
/// @title Routers
/// @notice A wrapper for all router contracts
contract Routers is
AugustusFees,
AugustusRFQRouter,
BalancerV2SwapExactAmountOut,
BalancerV2SwapExactAmountIn,
CurveV1SwapExactAmountIn,
CurveV2SwapExactAmountIn,
GenericSwapExactAmountOut,
GenericSwapExactAmountIn,
UniswapV2SwapExactAmountOut,
UniswapV2SwapExactAmountIn,
UniswapV3SwapExactAmountOut,
UniswapV3SwapExactAmountIn
{
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
address _weth,
uint256 _uniswapV3FactoryAndFF,
uint256 _uniswapV3PoolInitCodeHash,
uint256 _uniswapV2FactoryAndFF,
uint256 _uniswapV2PoolInitCodeHash,
address payable _balancerVault,
address _permit2,
address _rfq,
address payable _feeVault
)
AugustusFees(_feeVault)
AugustusRFQUtils(_rfq)
BalancerV2Utils(_balancerVault)
Permit2Utils(_permit2)
UniswapV2Utils(_uniswapV2FactoryAndFF, _uniswapV2PoolInitCodeHash)
UniswapV3Utils(_uniswapV3FactoryAndFF, _uniswapV3PoolInitCodeHash)
WETHUtils(_weth)
{ }
}
// SPDX-License-Identifier: MIT
/**
* Vendored on October 12, 2023 from:
* https://github.com/mudgen/diamond-3-hardhat/blob/main/contracts/libraries/LibDiamond.sol
*/
pragma solidity ^0.8.0;
/**
* \\
* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
* /*****************************************************************************
*/
import { IDiamondCut } from "../interfaces/IDiamondCut.sol";
// Remember to add the loupe functions from DiamondLoupeFacet to the diamond.
// The loupe functions are required by the EIP2535 Diamonds standard
error InitializationFunctionReverted(address _initializationContractAddress, bytes _calldata);
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint256 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
// Internal function version of diamondCut
function diamondCut(IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata) internal {
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function");
removeFunction(ds, oldFacetAddress, selector);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(ds, oldFacetAddress, selector);
}
}
function addFacet(DiamondStorage storage ds, address _facetAddress) internal {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length;
ds.facetAddresses.push(_facetAddress);
}
function addFunction(
DiamondStorage storage ds,
bytes4 _selector,
uint96 _selectorPosition,
address _facetAddress
)
internal
{
ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector);
ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;
}
function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal {
require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// an immutable function is a function defined directly in a diamond
require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition;
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
return;
}
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up error
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(error)
revert(add(32, error), returndata_size)
}
} else {
revert InitializationFunctionReverted(_init, _calldata);
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
// SPDX-License-Identifier: MIT
/**
* Vendored on October 12, 2023 from:
* https://github.com/mudgen/diamond-3-hardhat/blob/main/contracts/interfaces/IDiamondCut.sol
*/
pragma solidity ^0.8.0;
/**
* \\
* Author: Nick Mudge (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
* /*****************************************************************************
*/
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IBalancerV2SwapExactAmountIn } from "../../../interfaces/IBalancerV2SwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { BalancerV2Data } from "../../../AugustusV6Types.sol";
// Utils
import { BalancerV2Utils } from "../../../util/BalancerV2Utils.sol";
/// @title BalancerV2SwapExactAmountIn
/// @notice A contract for executing direct swapExactAmountIn on Balancer V2
abstract contract BalancerV2SwapExactAmountIn is IBalancerV2SwapExactAmountIn, BalancerV2Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBalancerV2SwapExactAmountIn
function swapExactAmountInOnBalancerV2(
BalancerV2Data calldata balancerData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata data
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference balancerData
uint256 quotedAmountOut = balancerData.quotedAmount;
uint256 beneficiaryAndApproveFlag = balancerData.beneficiaryAndApproveFlag;
uint256 amountIn = balancerData.fromAmount;
uint256 minAmountOut = balancerData.toAmount;
// Decode params
(IERC20 srcToken, IERC20 destToken, address payable beneficiary, bool approve) =
_decodeBalancerV2Params(beneficiaryAndApproveFlag, data);
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check if srcToken is ETH
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), amountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), amountIn);
}
// Check if approve is needed
if (approve) {
// Approve BALANCER_VAULT to spend srcToken
srcToken.approve(BALANCER_VAULT);
}
}
// Execute swap
_callBalancerV2(data);
// Check balance after swap
receivedAmount = destToken.getBalance(address(this));
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransfer(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { ICurveV1SwapExactAmountIn } from "../../../interfaces/ICurveV1SwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { CurveV1Data } from "../../../AugustusV6Types.sol";
// Utils
import { AugustusFees } from "../../../fees/AugustusFees.sol";
import { WETHUtils } from "../../../util/WETHUtils.sol";
import { Permit2Utils } from "../../../util/Permit2Utils.sol";
import { PauseUtils } from "../../../util/PauseUtils.sol";
/// @title CurveV1SwapExactAmountIn
/// @notice A contract for executing direct CurveV1 swaps
abstract contract CurveV1SwapExactAmountIn is
ICurveV1SwapExactAmountIn,
AugustusFees,
WETHUtils,
Permit2Utils,
PauseUtils
{
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ICurveV1SwapExactAmountIn
function swapExactAmountInOnCurveV1(
CurveV1Data calldata curveV1Data,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference curveV1Data
IERC20 srcToken = curveV1Data.srcToken;
IERC20 destToken = curveV1Data.destToken;
uint256 amountIn = curveV1Data.fromAmount;
uint256 minAmountOut = curveV1Data.toAmount;
uint256 quotedAmountOut = curveV1Data.quotedAmount;
address payable beneficiary = curveV1Data.beneficiary;
uint256 curveAssets = curveV1Data.curveAssets;
uint256 curveData = curveV1Data.curveData;
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Decode curveData
// 160 bits for curve exchange address
// 1 bit for approve flag
// 2 bits for wrap flag
// 2 bits for swap type flag
address exchange;
bool approveFlag;
uint256 wrapFlag;
uint256 swapType;
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
exchange := and(curveData, 0xffffffffffffffffffffffffffffffffffffffff)
approveFlag := and(shr(160, curveData), 1)
wrapFlag := and(shr(161, curveData), 3)
swapType := and(shr(163, curveData), 3)
}
// Check if srcToken is ETH
// Transfer srcToken to augustus if not ETH
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), amountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), amountIn);
}
// Check if approve flag is set
if (approveFlag) {
// Approve exchange
srcToken.approve(exchange);
}
} else {
// Check if approve flag is set
if (approveFlag) {
// Approve exchange
IERC20(WETH).approve(exchange);
}
}
// Execute swap
_executeSwapOnCurveV1(exchange, wrapFlag, swapType, curveAssets, amountIn);
// Check balance after swap and unwrap if needed
if (wrapFlag == 2) {
// Received amount is WETH balance
receivedAmount = IERC20(WETH).getBalance(address(this));
// Unwrap WETH
WETH.withdraw(receivedAmount - 1);
// Set receivedAmount to this contract's balance
receivedAmount = address(this).balance;
} else {
// Received amount is destToken balance
receivedAmount = destToken.getBalance(address(this));
}
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransfer(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
/*//////////////////////////////////////////////////////////////
PRIVATE
//////////////////////////////////////////////////////////////*/
function _executeSwapOnCurveV1(
address exchange,
uint256 wrapFlag,
uint256 swapType,
uint256 curveAssets,
uint256 fromAmount
)
private
{
// Load WETH address
address weth = address(WETH);
// solhint-disable-next-line no-inline-assembly
assembly {
// Load free memory pointer
let ptr := mload(64)
//-----------------------------------------------------------------------------------
// Wrap ETH if needed
//-----------------------------------------------------------------------------------
// Check if wrap src flag is set
if eq(wrapFlag, 1) {
// Prepare call data for WETH.deposit()
// Store function selector and
mstore(ptr, 0xd0e30db000000000000000000000000000000000000000000000000000000000) // deposit()
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), weth, callvalue(), ptr, 4, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
//-----------------------------------------------------------------------------------
// Execute swap
//-----------------------------------------------------------------------------------
// Prepare call data for external call
// Check swap type
switch swapType
// 0x01 for EXCHANGE_UNDERLYING
case 0x01 {
// Store function selector for function exchange_underlying(int128,int128,uint256,uint256)
mstore(ptr, 0xa6417ed600000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), shr(128, curveAssets)) // store index i
mstore(add(ptr, 36), and(curveAssets, 0xffffffffffffffffffffffffffffffff)) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, 0, ptr, 132, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
// 0x00(default) for EXCHANGE
default {
// check send eth wrap flag
switch eq(wrapFlag, 0x03)
// if it is not set, store selector for function exchange(int128,int128,uint256,uint256)
case 1 {
mstore(ptr, 0x3df0212400000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), shr(128, curveAssets)) // store index i
mstore(add(ptr, 36), and(curveAssets, 0xffffffffffffffffffffffffffffffff)) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, callvalue(), ptr, 132, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
// if it is set, store selector for function exchange(int128,int128,uint256,uint256)
default {
mstore(ptr, 0x3df0212400000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), shr(128, curveAssets)) // store index i
mstore(add(ptr, 36), and(curveAssets, 0xffffffffffffffffffffffffffffffff)) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, 0, ptr, 132, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { ICurveV2SwapExactAmountIn } from "../../../interfaces/ICurveV2SwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { CurveV2Data } from "../../../AugustusV6Types.sol";
// Utils
import { AugustusFees } from "../../../fees/AugustusFees.sol";
import { WETHUtils } from "../../../util/WETHUtils.sol";
import { Permit2Utils } from "../../../util/Permit2Utils.sol";
import { PauseUtils } from "../../../util/PauseUtils.sol";
/// @title CurveV2SwapExactAmountIn
/// @notice A contract for executing direct CurveV2 swaps
abstract contract CurveV2SwapExactAmountIn is
ICurveV2SwapExactAmountIn,
AugustusFees,
WETHUtils,
Permit2Utils,
PauseUtils
{
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ICurveV2SwapExactAmountIn
function swapExactAmountInOnCurveV2(
CurveV2Data calldata curveV2Data,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference curveData
IERC20 srcToken = curveV2Data.srcToken;
IERC20 destToken = curveV2Data.destToken;
uint256 amountIn = curveV2Data.fromAmount;
uint256 minAmountOut = curveV2Data.toAmount;
uint256 quotedAmountOut = curveV2Data.quotedAmount;
address payable beneficiary = curveV2Data.beneficiary;
uint256 i = curveV2Data.i;
uint256 j = curveV2Data.j;
address poolAddress = curveV2Data.poolAddress;
uint256 curveData = curveV2Data.curveData;
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Decode curveData
// 160 bits for curve exchange address
// 1 bit for approve flag
// 2 bits for wrap flag
// 2 bits for swap type flag
address exchange;
bool approveFlag;
uint256 wrapFlag;
uint256 swapType;
// solhint-disable-next-line no-inline-assembly
assembly {
exchange := and(curveData, 0xffffffffffffffffffffffffffffffffffffffff)
approveFlag := and(shr(160, curveData), 1)
wrapFlag := and(shr(161, curveData), 3)
swapType := and(shr(163, curveData), 3)
}
// Check if srcToken is ETH
// Transfer srcToken to augustus if not ETH
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), amountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), amountIn);
}
// Check if approve flag is set
if (approveFlag) {
// Approve exchange
srcToken.approve(exchange);
}
} else {
// Check if approve flag is set
if (approveFlag) {
// Approve exchange
IERC20(WETH).approve(exchange);
}
}
// Execute swap
_executeSwapOnCurveV2(exchange, wrapFlag, swapType, i, j, amountIn, poolAddress);
// Check balance after swap and unwrap if needed
if (wrapFlag == 2) {
// Received amount is WETH balance
receivedAmount = IERC20(WETH).getBalance(address(this));
// Unwrap WETH
WETH.withdraw(receivedAmount - 1);
// Set receivedAmount to this contract's balance
receivedAmount = address(this).balance;
} else {
// Received amount is destToken balance
receivedAmount = destToken.getBalance(address(this));
}
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransfer(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
/*//////////////////////////////////////////////////////////////
PRIVATE
//////////////////////////////////////////////////////////////*/
function _executeSwapOnCurveV2(
address exchange,
uint256 wrapFlag,
uint256 swapType,
uint256 i,
uint256 j,
uint256 fromAmount,
address poolAddress
)
private
{
// Load WETH address
address weth = address(WETH);
// solhint-disable-next-line no-inline-assembly
assembly {
// Load free memory pointer
let ptr := mload(64)
//-----------------------------------------------------------------------------------
// Wrap ETH if needed
//-----------------------------------------------------------------------------------
// Check if wrap src flag is set
if eq(wrapFlag, 1) {
// Prepare call data for WETH.deposit()
// Store function selector and
mstore(ptr, 0xd0e30db000000000000000000000000000000000000000000000000000000000) // deposit()
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), weth, callvalue(), ptr, 4, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
//-----------------------------------------------------------------------------------
// Execute swap
//-----------------------------------------------------------------------------------
// Prepare call data for external call
// Check swap type
switch swapType
// 0x01 for EXCHANGE_UNDERLYING
case 0x01 {
// Store function selector for function exchange_underlying(uint256,uint256,uint256,uint256)
mstore(ptr, 0x65b2489b00000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), i) // store index i
mstore(add(ptr, 36), j) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, 0, ptr, 132, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
// 0x02 for EXCHANGE_GENERIC_FACTORY_ZAP
case 0x02 {
// Store function selector for function exchange(address,uint256,uint256,uint256,uint256)
mstore(ptr, 0x64a1455800000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 4), poolAddress) // store poolAddress
mstore(add(ptr, 36), i) // store index i
mstore(add(ptr, 68), j) // store index j
mstore(add(ptr, 100), fromAmount) // store fromAmount
mstore(add(ptr, 132), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, 0, ptr, 164, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
// 0x00(default) for EXCHANGE
default {
// check send eth wrap flag
switch eq(wrapFlag, 0x03)
// if it is not set, store selector for function exchange(uint256,uint256,uint256,uint256,bool)
case 1 {
mstore(ptr, 0x394747c500000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), i) // store index i
mstore(add(ptr, 36), j) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
mstore(add(ptr, 132), 1) // store true
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, callvalue(), ptr, 164, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
// if it is set, store selector for function exchange(uint256,uint256,uint256,uint256)
default {
mstore(ptr, 0x5b41b90800000000000000000000000000000000000000000000000000000000) // store selector
mstore(add(ptr, 4), i) // store index i
mstore(add(ptr, 36), j) // store index j
mstore(add(ptr, 68), fromAmount) // store fromAmount
mstore(add(ptr, 100), 1) // store 1
// Perform the external call with the prepared calldata
// Check the outcome of the call and handle failure
if iszero(call(gas(), exchange, 0, ptr, 132, 0, 0)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IUniswapV2SwapExactAmountIn } from "../../../interfaces/IUniswapV2SwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { UniswapV2Data } from "../../../AugustusV6Types.sol";
// Utils
import { UniswapV2Utils } from "../../../util/UniswapV2Utils.sol";
/// @title UniswapV2SwapExactAmountIn
/// @notice A contract for executing direct swapExactAmountIn on UniswapV2 pools
abstract contract UniswapV2SwapExactAmountIn is IUniswapV2SwapExactAmountIn, UniswapV2Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IUniswapV2SwapExactAmountIn
function swapExactAmountInOnUniswapV2(
UniswapV2Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference uniData
IERC20 srcToken = uniData.srcToken;
IERC20 destToken = uniData.destToken;
uint256 amountIn = uniData.fromAmount;
uint256 minAmountOut = uniData.toAmount;
uint256 quotedAmountOut = uniData.quotedAmount;
address payable beneficiary = uniData.beneficiary;
bytes calldata pools = uniData.pools;
// Initialize payer
address payer = msg.sender;
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check if we need to wrap or permit
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
}
} else {
// If it is ETH. wrap it to WETH
WETH.deposit{ value: amountIn }();
// Set srcToken to WETH
srcToken = WETH;
// Set payer to this contract
payer = address(this);
}
// Execute swap
_callUniswapV2PoolsSwapExactIn(amountIn, srcToken, pools, payer, permit);
// Check if destToken is ETH and unwrap
if (address(destToken) == address(ERC20Utils.ETH)) {
// Check balance of WETH
receivedAmount = IERC20(WETH).getBalance(address(this));
// Unwrap WETH
WETH.withdraw(receivedAmount - 1);
// Set receivedAmount to this contract's balance
receivedAmount = address(this).balance;
} else {
// Othwerwise check balance of destToken
receivedAmount = destToken.getBalance(address(this));
}
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransfer(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IUniswapV3SwapExactAmountIn } from "../../../interfaces/IUniswapV3SwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
import { SafeCastLib } from "@solady/utils/SafeCastLib.sol";
// Types
import { UniswapV3Data } from "../../../AugustusV6Types.sol";
// Utils
import { UniswapV3Utils } from "../../../util/UniswapV3Utils.sol";
/// @title UniswapV3SwapExactAmountIn
/// @notice A contract for executing direct swapExactAmountIn on Uniswap V3
abstract contract UniswapV3SwapExactAmountIn is IUniswapV3SwapExactAmountIn, UniswapV3Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
using SafeCastLib for uint256;
/*//////////////////////////////////////////////////////////////
SWAP
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IUniswapV3SwapExactAmountIn
function swapExactAmountInOnUniswapV3(
UniswapV3Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference uniData
IERC20 srcToken = uniData.srcToken;
IERC20 destToken = uniData.destToken;
uint256 amountIn = uniData.fromAmount;
uint256 minAmountOut = uniData.toAmount;
uint256 quotedAmountOut = uniData.quotedAmount;
address payable beneficiary = uniData.beneficiary;
bytes calldata pools = uniData.pools;
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Address that will pay for the swap
address fromAddress = msg.sender;
// Check if we need to wrap or permit
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
}
} else {
// If it is ETH. wrap it to WETH
WETH.deposit{ value: amountIn }();
// Swap will be paid from this contract
fromAddress = address(this);
}
// Execute swap
receivedAmount = _callUniswapV3PoolsSwapExactAmountIn(amountIn.toInt256(), pools, fromAddress, permit);
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Check if destToken is ETH and unwrap
if (address(destToken) == address(ERC20Utils.ETH)) {
// Unwrap WETH
WETH.withdraw(receivedAmount);
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransferUniV3(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IBalancerV2SwapExactAmountOut } from "../../../interfaces/IBalancerV2SwapExactAmountOut.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { BalancerV2Data } from "../../../AugustusV6Types.sol";
// Utils
import { BalancerV2Utils } from "../../../util/BalancerV2Utils.sol";
/// @title BalancerV2SwapExactAmountOut
/// @notice A contract for executing direct swapExactAmountOut on BalancerV2 pools
abstract contract BalancerV2SwapExactAmountOut is IBalancerV2SwapExactAmountOut, BalancerV2Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBalancerV2SwapExactAmountOut
function swapExactAmountOutOnBalancerV2(
BalancerV2Data calldata balancerData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata data
)
external
payable
whenNotPaused
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference balancerData
uint256 quotedAmountIn = balancerData.quotedAmount;
uint256 beneficiaryAndApproveFlag = balancerData.beneficiaryAndApproveFlag;
uint256 maxAmountIn = balancerData.fromAmount;
uint256 amountOut = balancerData.toAmount;
// Decode params
(IERC20 srcToken, IERC20 destToken, address payable beneficiary, bool approve) =
_decodeBalancerV2Params(beneficiaryAndApproveFlag, data);
// Make sure srcToken and destToken are different
if (srcToken == destToken) {
revert ArbitrageNotSupported();
}
// Check if toAmount is valid
if (amountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check contract balance
uint256 balanceBefore = srcToken.getBalance(address(this));
// Check if srcToken is ETH
if (srcToken.isETH(maxAmountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), maxAmountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), maxAmountIn);
}
// Check if approve is needed
if (approve) {
// Approve BALANCER_VAULT to spend srcToken
srcToken.approve(BALANCER_VAULT);
}
} else {
// If srcToken is ETH, we have to deduct msg.value from balanceBefore
balanceBefore = balanceBefore - msg.value;
}
// Execute swap
_callBalancerV2(data);
// Check balance of destToken
receivedAmount = destToken.getBalance(address(this));
// Check balance of srcToken, deducting the balance before the swap if it is greater than 1
uint256 remainingAmount = srcToken.getBalance(address(this)) - (balanceBefore > 1 ? balanceBefore : 0);
// Check if swap succeeded
if (receivedAmount < amountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken and srcToken to beneficiary
return processSwapExactAmountOutFeesAndTransfer(
beneficiary,
srcToken,
destToken,
partnerAndFee,
maxAmountIn,
remainingAmount,
receivedAmount,
quotedAmountIn
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IUniswapV2SwapExactAmountOut } from "../../../interfaces/IUniswapV2SwapExactAmountOut.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
// Types
import { UniswapV2Data } from "../../../AugustusV6Types.sol";
// Utils
import { UniswapV2Utils } from "../../../util/UniswapV2Utils.sol";
/// @title UniswapV2SwapExactAmountOut
/// @notice A contract for executing direct swapExactAmountOut on UniswapV2 pools
abstract contract UniswapV2SwapExactAmountOut is IUniswapV2SwapExactAmountOut, UniswapV2Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IUniswapV2SwapExactAmountOut
function swapExactAmountOutOnUniswapV2(
UniswapV2Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference uniData
IERC20 srcToken = uniData.srcToken;
IERC20 destToken = uniData.destToken;
uint256 maxAmountIn = uniData.fromAmount;
uint256 amountOut = uniData.toAmount;
uint256 quotedAmountIn = uniData.quotedAmount;
address payable beneficiary = uniData.beneficiary;
bytes calldata pools = uniData.pools;
// Check if toAmount is valid
if (amountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Init balanceBefore
uint256 balanceBefore;
// Check if srcToken is ETH
bool isFromETH = srcToken.isETH(maxAmountIn) != 0;
// Check if we need to wrap or permit
if (isFromETH) {
// Check WETH balance before
balanceBefore = IERC20(WETH).getBalance(address(this));
// If it is ETH. wrap it to WETH
WETH.deposit{ value: maxAmountIn }();
// Set srcToken to WETH
srcToken = WETH;
} else {
// Check srcToken balance before
balanceBefore = srcToken.getBalance(address(this));
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), maxAmountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), maxAmountIn);
}
}
// Make sure srcToken and destToken are different
if (srcToken == destToken) {
revert ArbitrageNotSupported();
}
// Execute swap
_callUniswapV2PoolsSwapExactOut(amountOut, srcToken, pools);
// Check if destToken is ETH and unwrap
if (address(destToken) == address(ERC20Utils.ETH)) {
// Make sure srcToken was not WETH
if (srcToken == WETH) {
revert ArbitrageNotSupported();
}
// Check balance of WETH
receivedAmount = IERC20(WETH).getBalance(address(this));
// Leave dust if receivedAmount > amountOut
if (receivedAmount > amountOut) {
--receivedAmount;
}
// Unwrap WETH
WETH.withdraw(receivedAmount);
// Set receivedAmount to this contract's balance
receivedAmount = address(this).balance;
} else {
// Othwerwise check balance of destToken
receivedAmount = destToken.getBalance(address(this));
}
// Check balance of srcToken
uint256 remainingAmount = srcToken.getBalance(address(this));
// Check if swap succeeded
if (receivedAmount < amountOut) {
revert InsufficientReturnAmount();
}
// Check if srcToken is ETH and unwrap if there is remaining amount
if (isFromETH) {
// Check native balance before
uint256 nativeBalanceBefore = address(this).balance;
// If balanceBefore is greater than 1, deduct it from remainingAmount
remainingAmount = remainingAmount - (balanceBefore > 1 ? balanceBefore : 0);
// Withdraw remaining WETH if any
if (remainingAmount > 1) {
WETH.withdraw(remainingAmount - 1);
}
srcToken = ERC20Utils.ETH;
// If native balance before is greater than 1, deduct it from remainingAmount
remainingAmount = address(this).balance - (nativeBalanceBefore > 1 ? nativeBalanceBefore : 0);
} else {
// Otherwise, if balanceBefore is greater than 1, deduct it from remainingAmount
remainingAmount = remainingAmount - (balanceBefore > 1 ? balanceBefore : 0);
}
// Process fees and transfer destToken and srcToken to beneficiary
return processSwapExactAmountOutFeesAndTransfer(
beneficiary,
srcToken,
destToken,
partnerAndFee,
maxAmountIn,
remainingAmount,
receivedAmount,
quotedAmountIn
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IUniswapV3SwapExactAmountOut } from "../../../interfaces/IUniswapV3SwapExactAmountOut.sol";
// Libraries
import { ERC20Utils } from "../../../libraries/ERC20Utils.sol";
import { SafeCastLib } from "@solady/utils/SafeCastLib.sol";
// Types
import { UniswapV3Data } from "../../../AugustusV6Types.sol";
// Utils
import { UniswapV3Utils } from "../../../util/UniswapV3Utils.sol";
/// @title UniswapV3SwapExactAmountOut
/// @notice A contract for executing direct swapExactAmountOut on UniswapV3 pools
abstract contract UniswapV3SwapExactAmountOut is IUniswapV3SwapExactAmountOut, UniswapV3Utils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
using SafeCastLib for uint256;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IUniswapV3SwapExactAmountOut
function swapExactAmountOutOnUniswapV3(
UniswapV3Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference uniData
IERC20 srcToken = uniData.srcToken;
IERC20 destToken = uniData.destToken;
uint256 maxAmountIn = uniData.fromAmount;
uint256 amountOut = uniData.toAmount;
uint256 quotedAmountIn = uniData.quotedAmount;
address payable beneficiary = uniData.beneficiary;
bytes calldata pools = uniData.pools;
// Check if toAmount is valid
if (amountOut == 0) {
revert InvalidToAmount();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Address that will pay for the swap
address fromAddress = msg.sender;
// Check if srcToken is ETH
bool isFromETH = srcToken.isETH(maxAmountIn) != 0;
// If pools.length > 96, we are going to do a multi-pool swap
bool isMultiplePools = pools.length > 96;
// Init balance before variables
uint256 senderBalanceBefore;
uint256 balanceBefore;
// Check if we need to wrap or permit
if (isFromETH) {
// Check WETH balance before
balanceBefore = IERC20(WETH).getBalance(address(this));
// If it is ETH. wrap it to WETH
WETH.deposit{ value: maxAmountIn }();
// Swap will be paid from this contract
fromAddress = address(this);
// Set srcToken to WETH
srcToken = WETH;
} else {
// Check srcToken balance before
balanceBefore = srcToken.getBalance(address(this));
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
// if we're using multiple pools, we need to store the pre-swap balance of srcToken
if (isMultiplePools) {
senderBalanceBefore = srcToken.getBalance(msg.sender);
}
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), maxAmountIn);
// Swap will be paid from this contract
fromAddress = address(this);
}
}
// Make sure srcToken and destToken are different
if (srcToken == destToken) {
revert ArbitrageNotSupported();
}
// Execute swap
(spentAmount, receivedAmount) =
_callUniswapV3PoolsSwapExactAmountOut((-amountOut.toInt256()), pools, fromAddress);
// Check if swap succeeded
if (receivedAmount < amountOut) {
revert InsufficientReturnAmount();
}
// Check if destToken is ETH and unwrap
if (address(destToken) == address(ERC20Utils.ETH)) {
// Make sure srcToken was not WETH
if (srcToken == WETH) {
revert ArbitrageNotSupported();
}
// Unwrap WETH
WETH.withdraw(receivedAmount);
}
// Iniiialize remainingAmount
uint256 remainingAmount;
// Check if payer is this contract
if (fromAddress == address(this)) {
// If srcTokenwas ETH, we need to withdraw remaining WETH if any
if (isFromETH) {
// Check native balance before
uint256 nativeBalanceBefore = address(this).balance;
// Check balance of WETH, If balanceBefore is greater than 1, deduct it from remainingAmount
remainingAmount = IERC20(WETH).getBalance(address(this)) - (balanceBefore > 1 ? balanceBefore : 0);
// Withdraw remaining WETH if any
if (remainingAmount > 1) {
// Unwrap WETH
WETH.withdraw(remainingAmount - 1);
// If native balance before is greater than 1, deduct it from remainingAmount
remainingAmount = address(this).balance - (nativeBalanceBefore > 1 ? nativeBalanceBefore : 0);
}
// Set srcToken to ETH
srcToken = ERC20Utils.ETH;
} else {
// If we have executed multi-pool swap, we need to fetch the remaining amount from balance
if (isMultiplePools) {
// Calculate spent amount and remaining amount, If balanceBefore is greater than 1, deduct it from
// remainingAmount
remainingAmount = srcToken.getBalance(address(this)) - (balanceBefore > 1 ? balanceBefore : 0);
} else {
// Otherwise, remaining amount is the difference between the spent amount and the remaining balance
remainingAmount = maxAmountIn - spentAmount;
}
}
// Process fees using processSwapExactAmountOutFeesAndTransfer
return processSwapExactAmountOutFeesAndTransfer(
beneficiary,
srcToken,
destToken,
partnerAndFee,
maxAmountIn,
remainingAmount,
receivedAmount,
quotedAmountIn
);
} else {
// If we have executed multi-pool swap, we need to re-calculate the remaining amount and spent amount
if (isMultiplePools) {
// Calculate spent amount and remaining amount
remainingAmount = srcToken.getBalance(msg.sender);
spentAmount = senderBalanceBefore - remainingAmount;
}
// Process fees and transfer destToken and srcToken to feeVault or partner and
// feeWallet if needed
return processSwapExactAmountOutFeesAndTransferUniV3(
beneficiary,
srcToken,
destToken,
partnerAndFee,
maxAmountIn,
receivedAmount,
spentAmount,
quotedAmountIn
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IAugustusFeeVault } from "../interfaces/IAugustusFeeVault.sol";
import { IAugustusFees } from "../interfaces/IAugustusFees.sol";
// Libraries
import { ERC20Utils } from "../libraries/ERC20Utils.sol";
// Storage
import { AugustusStorage } from "../storage/AugustusStorage.sol";
/// @title AugustusFees
/// @notice Contract for handling fees
contract AugustusFees is AugustusStorage, IAugustusFees {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Fee share constants
uint256 public constant PARTNER_SHARE_PERCENT = 8500;
uint256 public constant MAX_FEE_PERCENT = 200;
uint256 public constant SURPLUS_PERCENT = 100;
uint256 public constant PARASWAP_REFERRAL_SHARE = 5000;
uint256 public constant PARTNER_REFERRAL_SHARE = 2500;
uint256 public constant PARASWAP_SURPLUS_SHARE = 5000;
uint256 public constant PARASWAP_SLIPPAGE_SHARE = 10_000;
uint256 public constant MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI = 11;
/// @dev Masks for unpacking feeData
uint256 private constant FEE_PERCENT_IN_BASIS_POINTS_MASK = 0x3FFF;
uint256 private constant IS_USER_SURPLUS_MASK = 1 << 90;
uint256 private constant IS_DIRECT_TRANSFER_MASK = 1 << 91;
uint256 private constant IS_CAP_SURPLUS_MASK = 1 << 92;
uint256 private constant IS_SKIP_BLACKLIST_MASK = 1 << 93;
uint256 private constant IS_REFERRAL_MASK = 1 << 94;
uint256 private constant IS_TAKE_SURPLUS_MASK = 1 << 95;
/// @dev A contact that stores fees collected by the protocol
IAugustusFeeVault public immutable FEE_VAULT; // solhint-disable-line var-name-mixedcase
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _feeVault) {
FEE_VAULT = IAugustusFeeVault(_feeVault);
}
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN FEES
//////////////////////////////////////////////////////////////*/
/// @notice Process swapExactAmountIn fees and transfer the received amount to the beneficiary
/// @param destToken The received token from the swapExactAmountIn
/// @param partnerAndFee Packed partner and fee data
/// @param receivedAmount The amount of destToken received from the swapExactAmountIn
/// @param quotedAmount The quoted expected amount of destToken
/// @return returnAmount The amount of destToken transfered to the beneficiary
/// @return paraswapFeeShare The share of the fees for Paraswap
/// @return partnerFeeShare The share of the fees for the partner
function processSwapExactAmountInFeesAndTransfer(
address beneficiary,
IERC20 destToken,
uint256 partnerAndFee,
uint256 receivedAmount,
uint256 quotedAmount
)
internal
returns (uint256 returnAmount, uint256 paraswapFeeShare, uint256 partnerFeeShare)
{
// initialize the surplus
uint256 surplus;
// parse partner and fee data
(address payable partner, uint256 feeData) = parsePartnerAndFeeData(partnerAndFee);
// calculate the surplus, we expect there to be 1 wei dust left which we should
// not take into account when determining if there is surplus, we only take the
// surplus if it is greater than MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI
if (receivedAmount > quotedAmount + MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI) {
surplus = receivedAmount - quotedAmount;
// if the cap surplus flag is passed, we cap the surplus to 1% of the quoted amount
if (feeData & IS_CAP_SURPLUS_MASK != 0) {
uint256 cappedSurplus = (SURPLUS_PERCENT * quotedAmount) / 10_000;
surplus = surplus > cappedSurplus ? cappedSurplus : surplus;
}
}
// calculate remainingAmount
uint256 remainingAmount = receivedAmount - surplus;
// if partner address is not 0x0
if (partner != address(0x0)) {
// Check if skip blacklist flag is true
bool skipBlacklist = feeData & IS_SKIP_BLACKLIST_MASK != 0;
// Check if token is blacklisted
bool isBlacklisted = blacklistedTokens[destToken];
// If the token is blacklisted and the skipBlacklist flag is false,
// send the received amount to the beneficiary, we won't process fees
if (!skipBlacklist && isBlacklisted) {
// transfer the received amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, receivedAmount);
return (receivedAmount - 1, 0, 0);
}
// Check if direct transfer flag is true
bool isDirectTransfer = feeData & IS_DIRECT_TRANSFER_MASK != 0;
// partner takes fixed fees feePercent is greater than 0
uint256 feePercent = _getAdjustedFeePercent(feeData);
if (feePercent > 0) {
// fee base = min (receivedAmount, quotedAmount + surplus)
uint256 feeBase = receivedAmount > quotedAmount + surplus ? quotedAmount + surplus : receivedAmount;
// calculate fixed fees
uint256 fee = (feeBase * feePercent) / 10_000;
partnerFeeShare = (fee * PARTNER_SHARE_PERCENT) / 10_000;
paraswapFeeShare = fee - partnerFeeShare;
// distrubite fees from destToken
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, returnAmount);
return (returnAmount - 1, paraswapFeeShare, partnerFeeShare);
}
// if slippage is postive and referral flag is true
else if (feeData & IS_REFERRAL_MASK != 0) {
if (surplus > 0) {
// the split is 50% for paraswap, 25% for the referrer and 25% for the user
paraswapFeeShare = (surplus * PARASWAP_REFERRAL_SHARE) / 10_000;
partnerFeeShare = (surplus * PARTNER_REFERRAL_SHARE) / 10_000;
// distribute fees from destToken
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, returnAmount);
return (returnAmount - 1, paraswapFeeShare, partnerFeeShare);
}
}
// if slippage is positive and takeSurplus flag is true
else if (feeData & IS_TAKE_SURPLUS_MASK != 0) {
if (surplus > 0) {
// paraswap takes 50% of the surplus and partner takes the other 50%
paraswapFeeShare = (surplus * PARASWAP_SURPLUS_SHARE) / 10_000;
partnerFeeShare = surplus - paraswapFeeShare;
// If user surplus flag is true, transfer the partner share to the user instead of the partner
if (feeData & IS_USER_SURPLUS_MASK != 0) {
partnerFeeShare = 0;
// Transfer the paraswap share directly to the fee wallet
isDirectTransfer = true;
}
// distrubite fees from destToken, partner takes 50% of the surplus
// and paraswap takes the other 50%
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, returnAmount);
return (returnAmount - 1, paraswapFeeShare, partnerFeeShare);
}
}
}
// if slippage is positive and partner address is 0x0 or fee percent is 0
// paraswap will take the surplus and transfer the rest to the beneficiary
// if there is no positive slippage, transfer the received amount to the beneficiary
if (surplus > 0) {
// If the token is blacklisted, send the received amount to the beneficiary
// we won't process fees
if (blacklistedTokens[destToken]) {
// transfer the received amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, receivedAmount);
return (receivedAmount - 1, 0, 0);
}
// transfer the remaining amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, remainingAmount);
// transfer the surplus to the fee wallet
destToken.safeTransfer(feeWallet, surplus);
return (remainingAmount - 1, surplus, 0);
} else {
// transfer the received amount to the beneficiary, keeping 1 wei dust
_transferAndLeaveDust(destToken, beneficiary, receivedAmount);
return (receivedAmount - 1, 0, 0);
}
}
/// @notice Process swapExactAmountIn fees and transfer the received amount to the beneficiary
/// @param destToken The received token from the swapExactAmountIn
/// @param partnerAndFee Packed partner and fee data
/// @param receivedAmount The amount of destToken received from the swapExactAmountIn
/// @param quotedAmount The quoted expected amount of destToken
/// @return returnAmount The amount of destToken transfered to the beneficiary
/// @return paraswapFeeShare The share of the fees for Paraswap
/// @return partnerFeeShare The share of the fees for the partner
function processSwapExactAmountInFeesAndTransferUniV3(
address beneficiary,
IERC20 destToken,
uint256 partnerAndFee,
uint256 receivedAmount,
uint256 quotedAmount
)
internal
returns (uint256 returnAmount, uint256 paraswapFeeShare, uint256 partnerFeeShare)
{
// initialize the surplus
uint256 surplus;
// parse partner and fee data
(address payable partner, uint256 feeData) = parsePartnerAndFeeData(partnerAndFee);
// calculate the surplus, we do not take the surplus into account if it is less than
// MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI
if (receivedAmount > quotedAmount + MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI) {
surplus = receivedAmount - quotedAmount;
// if the cap surplus flag is passed, we cap the surplus to 1% of the quoted amount
if (feeData & IS_CAP_SURPLUS_MASK != 0) {
uint256 cappedSurplus = (SURPLUS_PERCENT * quotedAmount) / 10_000;
surplus = surplus > cappedSurplus ? cappedSurplus : surplus;
}
}
// calculate remainingAmount
uint256 remainingAmount = receivedAmount - surplus;
// if partner address is not 0x0
if (partner != address(0x0)) {
// Check if skip blacklist flag is true
bool skipBlacklist = feeData & IS_SKIP_BLACKLIST_MASK != 0;
// Check if token is blacklisted
bool isBlacklisted = blacklistedTokens[destToken];
// If the token is blacklisted and the skipBlacklist flag is false,
// send the received amount to the beneficiary, we won't process fees
if (!skipBlacklist && isBlacklisted) {
// transfer the received amount to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (receivedAmount, 0, 0);
}
// Check if direct transfer flag is true
bool isDirectTransfer = feeData & IS_DIRECT_TRANSFER_MASK != 0;
// partner takes fixed fees feePercent is greater than 0
uint256 feePercent = _getAdjustedFeePercent(feeData);
if (feePercent > 0) {
// fee base = min (receivedAmount, quotedAmount + surplus)
uint256 feeBase = receivedAmount > quotedAmount + surplus ? quotedAmount + surplus : receivedAmount;
// calculate fixed fees
uint256 fee = (feeBase * feePercent) / 10_000;
partnerFeeShare = (fee * PARTNER_SHARE_PERCENT) / 10_000;
paraswapFeeShare = fee - partnerFeeShare;
// distrubite fees from destToken
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary
destToken.safeTransfer(beneficiary, returnAmount);
return (returnAmount, paraswapFeeShare, partnerFeeShare);
}
// if slippage is postive and referral flag is true
else if (feeData & IS_REFERRAL_MASK != 0) {
if (surplus > 0) {
// the split is 50% for paraswap, 25% for the referrer and 25% for the user
paraswapFeeShare = (surplus * PARASWAP_REFERRAL_SHARE) / 10_000;
partnerFeeShare = (surplus * PARTNER_REFERRAL_SHARE) / 10_000;
// distribute fees from destToken
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary
destToken.safeTransfer(beneficiary, returnAmount);
return (returnAmount, paraswapFeeShare, partnerFeeShare);
}
}
// if slippage is positive and takeSurplus flag is true
else if (feeData & IS_TAKE_SURPLUS_MASK != 0) {
if (surplus > 0) {
// paraswap takes 50% of the surplus and partner takes the other 50%
paraswapFeeShare = (surplus * PARASWAP_SURPLUS_SHARE) / 10_000;
partnerFeeShare = surplus - paraswapFeeShare;
// If user surplus flag is true, transfer the partner share to the user instead of the partner
if (feeData & IS_USER_SURPLUS_MASK != 0) {
partnerFeeShare = 0;
// Transfer the paraswap share directly to the fee wallet
isDirectTransfer = true;
}
// distrubite fees from destToken, partner takes 50% of the surplus
// and paraswap takes the other 50%
returnAmount = _distributeFees(
receivedAmount,
destToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the return amount to the beneficiary,
destToken.safeTransfer(beneficiary, returnAmount);
return (returnAmount, paraswapFeeShare, partnerFeeShare);
}
}
}
// if slippage is positive and partner address is 0x0 or fee percent is 0
// paraswap will take the surplus and transfer the rest to the beneficiary
// if there is no positive slippage, transfer the received amount to the beneficiary
if (surplus > 0) {
// If the token is blacklisted, send the received amount to the beneficiary
// we won't process fees
if (blacklistedTokens[destToken]) {
// transfer the received amount to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (receivedAmount, 0, 0);
}
// transfer the remaining amount to the beneficiary
destToken.safeTransfer(beneficiary, remainingAmount);
// transfer the surplus to the fee wallet
destToken.safeTransfer(feeWallet, surplus);
return (remainingAmount, surplus, 0);
} else {
// transfer the received amount to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (receivedAmount, 0, 0);
}
}
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT FEES
//////////////////////////////////////////////////////////////*/
/// @notice Process swapExactAmountOut fees and transfer the received amount and remaining amount to the
/// beneficiary
/// @param srcToken The token used to swapExactAmountOut
/// @param destToken The token received from the swapExactAmountOut
/// @param partnerAndFee Packed partner and fee data
/// @param maxAmountIn The amount of srcToken passed to the swapExactAmountOut
/// @param receivedAmount The amount of destToken received from the swapExactAmountOut
/// @param quotedAmount The quoted expected amount of srcToken to be used to swapExactAmountOut
/// @return spentAmount The amount of srcToken used to swapExactAmountOut
/// @return outAmount The amount of destToken transfered to the beneficiary
/// @return paraswapFeeShare The share of the fees for Paraswap
/// @return partnerFeeShare The share of the fees for the partner
function processSwapExactAmountOutFeesAndTransfer(
address beneficiary,
IERC20 srcToken,
IERC20 destToken,
uint256 partnerAndFee,
uint256 maxAmountIn,
uint256 remainingAmount,
uint256 receivedAmount,
uint256 quotedAmount
)
internal
returns (uint256 spentAmount, uint256 outAmount, uint256 paraswapFeeShare, uint256 partnerFeeShare)
{
// calculate the amount used to swapExactAmountOut
spentAmount = maxAmountIn - (remainingAmount > 0 ? remainingAmount - 1 : remainingAmount);
// initialize the surplus
uint256 surplus;
// initialize the return amount
uint256 returnAmount;
// parse partner and fee data
(address payable partner, uint256 feeData) = parsePartnerAndFeeData(partnerAndFee);
// check if the quotedAmount is bigger than the maxAmountIn
if (quotedAmount > maxAmountIn) {
revert InvalidQuotedAmount();
}
// calculate the surplus, we do not take the surplus into account if it is less than
// MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI
if (quotedAmount > spentAmount + MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI) {
surplus = quotedAmount - spentAmount;
// if the cap surplus flag is passed, we cap the surplus to 1% of the quoted amount
if (feeData & IS_CAP_SURPLUS_MASK != 0) {
uint256 cappedSurplus = (SURPLUS_PERCENT * quotedAmount) / 10_000;
surplus = surplus > cappedSurplus ? cappedSurplus : surplus;
}
}
// if partner address is not 0x0
if (partner != address(0x0)) {
// Check if skip blacklist flag is true
bool skipBlacklist = feeData & IS_SKIP_BLACKLIST_MASK != 0;
// Check if token is blacklisted
bool isBlacklisted = blacklistedTokens[srcToken];
// If the token is blacklisted and the skipBlacklist flag is false,
// send the remaining amount to the msg.sender, we won't process fees
if (!skipBlacklist && isBlacklisted) {
// transfer the remaining amount to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, remainingAmount);
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, --receivedAmount);
return (maxAmountIn - returnAmount, receivedAmount, 0, 0);
}
// Check if direct transfer flag is true
bool isDirectTransfer = feeData & IS_DIRECT_TRANSFER_MASK != 0;
// partner takes fixed fees feePercent is greater than 0
uint256 feePercent = _getAdjustedFeePercent(feeData);
if (feePercent > 0) {
// fee base = min (spentAmount, quotedAmount)
uint256 feeBase = spentAmount < quotedAmount ? spentAmount : quotedAmount;
// calculate fixed fees
uint256 fee = (feeBase * feePercent) / 10_000;
partnerFeeShare = (fee * PARTNER_SHARE_PERCENT) / 10_000;
paraswapFeeShare = fee - partnerFeeShare;
// distrubite fees from srcToken
returnAmount = _distributeFees(
remainingAmount,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the rest to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, returnAmount);
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, --receivedAmount);
return (maxAmountIn - returnAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
// if slippage is postive and referral flag is true
if (feeData & IS_REFERRAL_MASK != 0) {
if (surplus > 0) {
// the split is 50% for paraswap, 25% for the referrer and 25% for the user
paraswapFeeShare = (surplus * PARASWAP_REFERRAL_SHARE) / 10_000;
partnerFeeShare = (surplus * PARTNER_REFERRAL_SHARE) / 10_000;
// distribute fees from srcToken
returnAmount = _distributeFees(
remainingAmount,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the rest to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, returnAmount);
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, --receivedAmount);
return (maxAmountIn - returnAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
}
// if slippage is positive and takeSurplus flag is true
else if (feeData & IS_TAKE_SURPLUS_MASK != 0) {
if (surplus > 0) {
// paraswap takes 50% of the surplus and partner takes the other 50%
paraswapFeeShare = (surplus * PARASWAP_SURPLUS_SHARE) / 10_000;
partnerFeeShare = surplus - paraswapFeeShare;
// If user surplus flag is true, transfer the partner share to the user instead of the partner
if (feeData & IS_USER_SURPLUS_MASK != 0) {
partnerFeeShare = 0;
// Transfer the paraswap share directly to the fee wallet
isDirectTransfer = true;
}
// distrubite fees from srcToken, partner takes 50% of the surplus
// and paraswap takes the other 50%
returnAmount = _distributeFees(
remainingAmount,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
);
// transfer the rest to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, returnAmount);
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, --receivedAmount);
return (maxAmountIn - returnAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
}
}
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, --receivedAmount);
// if slippage is positive and partner address is 0x0 or fee percent is 0
// paraswap will take the surplus, and transfer the rest to msg.sender
// if there is no positive slippage, transfer the remaining amount to msg.sender
if (surplus > 0) {
// If the token is blacklisted, send the remaining amount to the msg.sender
// we won't process fees
if (blacklistedTokens[srcToken]) {
// transfer the remaining amount to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, remainingAmount);
return (maxAmountIn - returnAmount, receivedAmount, 0, 0);
}
// transfer the surplus to the fee wallet
srcToken.safeTransfer(feeWallet, surplus);
// transfer the remaining amount to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, remainingAmount - surplus);
return (maxAmountIn - returnAmount, receivedAmount, surplus, 0);
} else {
// transfer the remaining amount to msg.sender
returnAmount = _transferIfGreaterThanOne(srcToken, msg.sender, remainingAmount);
return (maxAmountIn - returnAmount, receivedAmount, 0, 0);
}
}
/// @notice Process swapExactAmountOut fees for UniV3 swapExactAmountOut, doing a transferFrom user to the fee
/// vault or partner and feeWallet
/// @param beneficiary The user's address
/// @param srcToken The token used to swapExactAmountOut
/// @param destToken The token received from the swapExactAmountOut
/// @param partnerAndFee Packed partner and fee data
/// @param maxAmountIn The amount of srcToken passed to the swapExactAmountOut
/// @param receivedAmount The amount of destToken received from the swapExactAmountOut
/// @param spentAmount The amount of srcToken used to swapExactAmountOut
/// @param quotedAmount The quoted expected amount of srcToken to be used to swapExactAmountOut
/// @return totalSpentAmount The total amount of srcToken used to swapExactAmountOut
/// @return returnAmount The amount of destToken transfered to the beneficiary
/// @return paraswapFeeShare The share of the fees for Paraswap
/// @return partnerFeeShare The share of the fees for the partner
function processSwapExactAmountOutFeesAndTransferUniV3(
address beneficiary,
IERC20 srcToken,
IERC20 destToken,
uint256 partnerAndFee,
uint256 maxAmountIn,
uint256 receivedAmount,
uint256 spentAmount,
uint256 quotedAmount
)
internal
returns (uint256 totalSpentAmount, uint256 returnAmount, uint256 paraswapFeeShare, uint256 partnerFeeShare)
{
// initialize the surplus
uint256 surplus;
// calculate remaining amount
uint256 remainingAmount = maxAmountIn - spentAmount;
// parse partner and fee data
(address payable partner, uint256 feeData) = parsePartnerAndFeeData(partnerAndFee);
// check if the quotedAmount is bigger than the fromAmount
if (quotedAmount > maxAmountIn) {
revert InvalidQuotedAmount();
}
// calculate the surplus, we do not take the surplus into account if it is less than
// MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI
if (quotedAmount > spentAmount + MINIMUM_SURPLUS_EPSILON_AND_ONE_WEI) {
surplus = quotedAmount - spentAmount;
// if the cap surplus flag is passed, we cap the surplus to 1% of the quoted amount
if (feeData & IS_CAP_SURPLUS_MASK != 0) {
uint256 cappedSurplus = (SURPLUS_PERCENT * quotedAmount) / 10_000;
surplus = surplus > cappedSurplus ? cappedSurplus : surplus;
}
}
// if partner address is not 0x0
if (partner != address(0x0)) {
// Check if skip blacklist flag is true
bool skipBlacklist = feeData & IS_SKIP_BLACKLIST_MASK != 0;
// Check if token is blacklisted
bool isBlacklisted = blacklistedTokens[srcToken];
// If the token is blacklisted and the skipBlacklist flag is false,
// we won't process fees
if (!skipBlacklist && isBlacklisted) {
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (spentAmount, receivedAmount, 0, 0);
}
// Check if direct transfer flag is true
bool isDirectTransfer = feeData & IS_DIRECT_TRANSFER_MASK != 0;
// partner takes fixed fees feePercent is greater than 0
uint256 feePercent = _getAdjustedFeePercent(feeData);
if (feePercent > 0) {
// fee base = min (spentAmount, quotedAmount)
uint256 feeBase = spentAmount < quotedAmount ? spentAmount : quotedAmount;
// calculate fixed fees
uint256 fee = (feeBase * feePercent) / 10_000;
partnerFeeShare = (fee * PARTNER_SHARE_PERCENT) / 10_000;
paraswapFeeShare = fee - partnerFeeShare;
// distrubite fees from srcToken
totalSpentAmount = _distributeFeesUniV3(
remainingAmount,
msg.sender,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
) + spentAmount;
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (totalSpentAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
// if slippage is postive and referral flag is true
else if (feeData & IS_REFERRAL_MASK != 0) {
if (surplus > 0) {
// the split is 50% for paraswap, 25% for the referrer and 25% for the user
paraswapFeeShare = (surplus * PARASWAP_REFERRAL_SHARE) / 10_000;
partnerFeeShare = (surplus * PARTNER_REFERRAL_SHARE) / 10_000;
// distribute fees from srcToken
totalSpentAmount = _distributeFeesUniV3(
remainingAmount,
msg.sender,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
) + spentAmount;
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (totalSpentAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
}
// if slippage is positive and takeSurplus flag is true
else if (feeData & IS_TAKE_SURPLUS_MASK != 0) {
if (surplus > 0) {
// paraswap takes 50% of the surplus and partner takes the other 50%
paraswapFeeShare = (surplus * PARASWAP_SURPLUS_SHARE) / 10_000;
partnerFeeShare = surplus - paraswapFeeShare;
// If user surplus flag is true, transfer the partner share to the user instead of the partner
if (feeData & IS_USER_SURPLUS_MASK != 0) {
partnerFeeShare = 0;
// Transfer the paraswap share directly to the fee wallet
isDirectTransfer = true;
}
// partner takes 50% of the surplus and paraswap takes the other 50%
// distrubite fees from srcToken
totalSpentAmount = _distributeFeesUniV3(
remainingAmount,
msg.sender,
srcToken,
partner,
partnerFeeShare,
paraswapFeeShare,
skipBlacklist,
isBlacklisted,
isDirectTransfer
) + spentAmount;
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
return (totalSpentAmount, receivedAmount, paraswapFeeShare, partnerFeeShare);
}
}
}
// transfer the received amount of destToken to the beneficiary
destToken.safeTransfer(beneficiary, receivedAmount);
// if slippage is positive and partner address is 0x0 or fee percent is 0
// paraswap will take the surplus
if (surplus > 0) {
// If the token is blacklisted, we won't process fees
if (blacklistedTokens[srcToken]) {
return (spentAmount, receivedAmount, 0, 0);
}
// transfer the surplus to the fee wallet
srcToken.safeTransferFrom(msg.sender, feeWallet, surplus);
}
return (spentAmount + surplus, receivedAmount, surplus, 0);
}
/*//////////////////////////////////////////////////////////////
PUBLIC
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IAugustusFees
function parsePartnerAndFeeData(uint256 partnerAndFee)
public
pure
returns (address payable partner, uint256 feeData)
{
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
partner := shr(96, partnerAndFee)
feeData := and(partnerAndFee, 0xFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/*//////////////////////////////////////////////////////////////
PRIVATE
//////////////////////////////////////////////////////////////*/
/// @notice Distribute fees to the partner and paraswap
/// @param currentBalance The current balance of the token before distributing the fees
/// @param token The token to distribute the fees for
/// @param partner The partner address
/// @param partnerShare The partner share
/// @param paraswapShare The paraswap share
/// @param skipBlacklist Whether to skip the blacklist and transfer the fees directly to the partner
/// @param isBlacklisted Whether the token is blacklisted
/// @param directTransfer Whether to transfer the fees directly to the partner instead of the fee vault
/// @return newBalance The new balance of the token after distributing the fees
function _distributeFees(
uint256 currentBalance,
IERC20 token,
address payable partner,
uint256 partnerShare,
uint256 paraswapShare,
bool skipBlacklist,
bool isBlacklisted,
bool directTransfer
)
private
returns (uint256 newBalance)
{
uint256 totalFees = partnerShare + paraswapShare;
if (totalFees == 0) {
return currentBalance;
} else {
if (skipBlacklist && isBlacklisted) {
// totalFees should be just the partner share, paraswap does not take fees
// on blacklisted tokens, the rest of the fees are sent to sender based on
// newBalance = currentBalance - totalFees
totalFees = partnerShare;
// revert if the balance is not enough to pay the fees
if (totalFees > currentBalance) {
revert InsufficientBalanceToPayFees();
}
if (partnerShare > 0) {
token.safeTransfer(partner, partnerShare);
}
} else {
// revert if the balance is not enough to pay the fees
if (totalFees > currentBalance) {
revert InsufficientBalanceToPayFees();
}
if (directTransfer) {
// transfer the fees directly to the partner and paraswap
if (paraswapShare > 0) {
token.safeTransfer(feeWallet, paraswapShare);
}
if (partnerShare > 0) {
token.safeTransfer(partner, partnerShare);
}
} else {
// transfer the fees to the fee vault
token.safeTransfer(address(FEE_VAULT), totalFees);
// Setup fee registration data
address[] memory feeAddresses = new address[](2);
uint256[] memory feeAmounts = new uint256[](2);
feeAddresses[0] = partner;
feeAmounts[0] = partnerShare;
feeAddresses[1] = feeWalletDelegate;
feeAmounts[1] = paraswapShare;
IAugustusFeeVault.FeeRegistration memory feeData =
IAugustusFeeVault.FeeRegistration({ token: token, addresses: feeAddresses, fees: feeAmounts });
// Register the fees
FEE_VAULT.registerFees(feeData);
}
}
}
newBalance = currentBalance - totalFees;
}
/// @notice Distribute fees for UniV3
/// @param currentBalance The current balance of the token before distributing the fees
/// @param payer The user's address
/// @param token The token to distribute the fees for
/// @param partner The partner address
/// @param partnerShare The partner share
/// @param paraswapShare The paraswap share
/// @param skipBlacklist Whether to skip the blacklist and transfer the fees directly to the partner
/// @param isBlacklisted Whether the token is blacklisted
/// @param directTransfer Whether to transfer the fees directly to the partner instead of the fee vault
/// @return totalFees The total fees distributed
function _distributeFeesUniV3(
uint256 currentBalance,
address payer,
IERC20 token,
address payable partner,
uint256 partnerShare,
uint256 paraswapShare,
bool skipBlacklist,
bool isBlacklisted,
bool directTransfer
)
private
returns (uint256 totalFees)
{
totalFees = partnerShare + paraswapShare;
if (totalFees != 0) {
if (skipBlacklist && isBlacklisted) {
// totalFees should be just the partner share, paraswap does not take fees
// on blacklisted tokens, the rest of the fees will remain on the payer's address
totalFees = partnerShare;
// revert if the balance is not enough to pay the fees
if (totalFees > currentBalance) {
revert InsufficientBalanceToPayFees();
}
// transfer the fees to the partner
if (partnerShare > 0) {
// transfer the fees to the partner
token.safeTransferFrom(payer, partner, partnerShare);
}
} else {
// revert if the balance is not enough to pay the fees
if (totalFees > currentBalance) {
revert InsufficientBalanceToPayFees();
}
if (directTransfer) {
// transfer the fees directly to the partner and paraswap
if (paraswapShare > 0) {
token.safeTransferFrom(payer, feeWallet, paraswapShare);
}
if (partnerShare > 0) {
token.safeTransferFrom(payer, partner, partnerShare);
}
} else {
// transfer the fees to the fee vault
token.safeTransferFrom(payer, address(FEE_VAULT), totalFees);
// Setup fee registration data
address[] memory feeAddresses = new address[](2);
uint256[] memory feeAmounts = new uint256[](2);
feeAddresses[0] = partner;
feeAmounts[0] = partnerShare;
feeAddresses[1] = feeWalletDelegate;
feeAmounts[1] = paraswapShare;
IAugustusFeeVault.FeeRegistration memory feeData =
IAugustusFeeVault.FeeRegistration({ token: token, addresses: feeAddresses, fees: feeAmounts });
// Register the fees
FEE_VAULT.registerFees(feeData);
}
}
// othwerwise do not transfer the fees
}
return totalFees;
}
/// @notice Get the adjusted fee percent by masking feePercent with FEE_PERCENT_IN_BASIS_POINTS_MASK,
/// if the fee percent is bigger than MAX_FEE_PERCENT, then set it to MAX_FEE_PERCENT
/// @param feePercent The fee percent
/// @return adjustedFeePercent The adjusted fee percent
function _getAdjustedFeePercent(uint256 feePercent) private pure returns (uint256) {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
feePercent := and(feePercent, FEE_PERCENT_IN_BASIS_POINTS_MASK)
// if feePercent is bigger than MAX_FEE_PERCENT, then set it to MAX_FEE_PERCENT
if gt(feePercent, MAX_FEE_PERCENT) { feePercent := MAX_FEE_PERCENT }
}
return feePercent;
}
/// @notice Transfers amount to recipient if the amount is bigger than 1, leaving 1 wei dust on the contract
/// @param token The token to transfer
/// @param recipient The address to transfer to
/// @param amount The amount to transfer
function _transferIfGreaterThanOne(
IERC20 token,
address recipient,
uint256 amount
)
private
returns (uint256 amountOut)
{
if (amount > 1) {
unchecked {
--amount;
}
token.safeTransfer(recipient, amount);
return amount;
}
return 0;
}
/// @notice Transfer amount to beneficiary, leaving 1 wei dust on the contract
/// @param token The token to transfer
/// @param beneficiary The address to transfer to
/// @param amount The amount to transfer
function _transferAndLeaveDust(IERC20 token, address beneficiary, uint256 amount) private {
unchecked {
--amount;
}
token.safeTransfer(beneficiary, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Contracts
import { GenericUtils } from "../../util/GenericUtils.sol";
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IGenericSwapExactAmountIn } from "../../interfaces/IGenericSwapExactAmountIn.sol";
// Libraries
import { ERC20Utils } from "../../libraries/ERC20Utils.sol";
// Types
import { GenericData } from "../../AugustusV6Types.sol";
/// @title GenericSwapExactAmountIn
/// @notice Router for executing generic swaps with exact amount in through an executor
abstract contract GenericSwapExactAmountIn is IGenericSwapExactAmountIn, GenericUtils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IGenericSwapExactAmountIn
function swapExactAmountIn(
address executor,
GenericData calldata swapData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata executorData
)
external
payable
whenNotPaused
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference swapData
IERC20 destToken = swapData.destToken;
IERC20 srcToken = swapData.srcToken;
uint256 amountIn = swapData.fromAmount;
uint256 minAmountOut = swapData.toAmount;
uint256 quotedAmountOut = swapData.quotedAmount;
address payable beneficiary = swapData.beneficiary;
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check if toAmount is valid
if (minAmountOut == 0) {
revert InvalidToAmount();
}
// Check if srcToken is ETH
if (srcToken.isETH(amountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, executor, amountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, executor, amountIn);
}
}
// Execute swap
_callSwapExactAmountInExecutor(executor, executorData, amountIn);
// Check balance after swap
receivedAmount = destToken.getBalance(address(this));
// Check if swap succeeded
if (receivedAmount < minAmountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken to beneficiary
return processSwapExactAmountInFeesAndTransfer(
beneficiary, destToken, partnerAndFee, receivedAmount, quotedAmountOut
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IGenericSwapExactAmountOut } from "../../interfaces/IGenericSwapExactAmountOut.sol";
// Libraries
import { ERC20Utils } from "../../libraries/ERC20Utils.sol";
// Types
import { GenericData } from "../../AugustusV6Types.sol";
// Utils
import { GenericUtils } from "../../util/GenericUtils.sol";
/// @title GenericSwapExactAmountOut
/// @notice Router for executing generic swaps with exact amount out through an executor
abstract contract GenericSwapExactAmountOut is IGenericSwapExactAmountOut, GenericUtils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IGenericSwapExactAmountOut
function swapExactAmountOut(
address executor,
GenericData calldata swapData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata executorData
)
external
payable
whenNotPaused
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare)
{
// Dereference swapData
IERC20 destToken = swapData.destToken;
IERC20 srcToken = swapData.srcToken;
uint256 maxAmountIn = swapData.fromAmount;
uint256 amountOut = swapData.toAmount;
uint256 quotedAmountIn = swapData.quotedAmount;
address payable beneficiary = swapData.beneficiary;
// Make sure srcToken and destToken are different
if (srcToken == destToken) {
revert ArbitrageNotSupported();
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check if toAmount is valid
if (amountOut == 0) {
revert InvalidToAmount();
}
// Check contract balance
uint256 balanceBefore = srcToken.getBalance(address(this));
// Check if srcToken is ETH
// Transfer srcToken to executor if not ETH
if (srcToken.isETH(maxAmountIn) == 0) {
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, executor, maxAmountIn);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, executor, maxAmountIn);
}
} else {
// If srcToken is ETH, we have to deduct msg.value from balanceBefore
balanceBefore = balanceBefore - msg.value;
}
// Execute swap
_callSwapExactAmountOutExecutor(executor, executorData, maxAmountIn, amountOut);
// Check balance of destToken
receivedAmount = destToken.getBalance(address(this));
// Check balance of srcToken, deducting the balance before the swap if it is greater than 1
uint256 remainingAmount = srcToken.getBalance(address(this)) - (balanceBefore > 1 ? balanceBefore : 0);
// Check if swap succeeded
if (receivedAmount < amountOut) {
revert InsufficientReturnAmount();
}
// Process fees and transfer destToken and srcToken to beneficiary
return processSwapExactAmountOutFeesAndTransfer(
beneficiary,
srcToken,
destToken,
partnerAndFee,
maxAmountIn,
remainingAmount,
receivedAmount,
quotedAmountIn
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
import { IAugustusRFQRouter } from "../../interfaces/IAugustusRFQRouter.sol";
// Libraries
import { ERC20Utils } from "../../libraries/ERC20Utils.sol";
// Types
import { AugustusRFQData, OrderInfo } from "../../AugustusV6Types.sol";
// Utils
import { AugustusRFQUtils } from "../../util/AugustusRFQUtils.sol";
import { WETHUtils } from "../../util/WETHUtils.sol";
import { PauseUtils } from "../../util/PauseUtils.sol";
import { Permit2Utils } from "../../util/Permit2Utils.sol";
import { AugustusFees } from "../../fees/AugustusFees.sol";
/// @title AugustusRFQRouter
/// @notice A contract for executing direct AugustusRFQ swaps
abstract contract AugustusRFQRouter is
IAugustusRFQRouter,
AugustusRFQUtils,
AugustusFees,
WETHUtils,
Permit2Utils,
PauseUtils
{
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
TRY BATCH FILL
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IAugustusRFQRouter
// solhint-disable-next-line code-complexity
function swapOnAugustusRFQTryBatchFill(
AugustusRFQData calldata data,
OrderInfo[] calldata orders,
bytes calldata permit
)
external
payable
whenNotPaused
returns (uint256 spentAmount, uint256 receivedAmount)
{
// Dereference data
address payable beneficiary = data.beneficiary;
uint256 ordersLength = orders.length;
uint256 fromAmount = data.fromAmount;
uint256 toAmount = data.toAmount;
uint8 wrapApproveDirection = data.wrapApproveDirection;
// Decode wrapApproveDirection
// First 2 bits are for wrap
// Next 1 bit is for approve
// Last 1 bit is for direction
uint8 wrap;
bool approve;
bool direction;
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
wrap := and(3, wrapApproveDirection)
approve := and(shr(2, wrapApproveDirection), 1)
direction := and(shr(3, wrapApproveDirection), 1)
}
// Check if beneficiary is valid
if (beneficiary == address(0)) {
beneficiary = payable(msg.sender);
}
// Check if toAmount is valid
if (toAmount == 0) {
revert InvalidToAmount();
}
// Check if ordersLength is valid
if (ordersLength == 0) {
revert InvalidOrdersLength();
}
// Check if msg.sender is authorized to be the taker for all orders
for (uint256 i = 0; i < ordersLength; ++i) {
_checkAuthorization(orders[i].order.nonceAndMeta);
}
// Dereference srcToken and destToken
IERC20 srcToken = IERC20(orders[0].order.takerAsset);
IERC20 destToken = IERC20(orders[0].order.makerAsset);
// Check if we need to wrap or permit
if (wrap != 1) {
// If msg.value is not 0, revert
if (msg.value > 0) {
revert IncorrectEthAmount();
}
// Check the length of the permit field,
// if < 257 and > 0 we should execute regular permit
// and if it is >= 257 we execute permit2
if (permit.length < 257) {
// Permit if needed
if (permit.length > 0) {
srcToken.permit(permit);
}
srcToken.safeTransferFrom(msg.sender, address(this), fromAmount);
} else {
// Otherwise Permit2.permitTransferFrom
permit2TransferFrom(permit, address(this), fromAmount);
}
} else {
// Check if msg.value is equal to fromAmount
if (fromAmount != msg.value) {
revert IncorrectEthAmount();
}
// If it is ETH. wrap it to WETH
WETH.deposit{ value: fromAmount }();
}
if (approve) {
// Approve srcToken to AugustusRFQ
srcToken.approve(address(AUGUSTUS_RFQ));
}
// Check if we need to execute a swapExactAmountIn or a swapExactAmountOut
if (!direction) {
// swapExactAmountIn
// Unwrap WETH if needed
if (wrap == 2) {
// Execute tryBatchFillOrderTakerAmount
AUGUSTUS_RFQ.tryBatchFillOrderTakerAmount(orders, fromAmount, address(this));
// Check received amount
receivedAmount = IERC20(WETH).getBalance(address(this));
// Check if swap succeeded
if (receivedAmount < toAmount) {
revert InsufficientReturnAmount();
}
// Unwrap WETH
WETH.withdraw(--receivedAmount);
// Transfer ETH to beneficiary
ERC20Utils.ETH.safeTransfer(beneficiary, receivedAmount);
} else {
// Check balance of beneficiary before swap
uint256 beforeBalance = destToken.getBalance(beneficiary);
// Execute tryBatchFillOrderTakerAmount
AUGUSTUS_RFQ.tryBatchFillOrderTakerAmount(orders, fromAmount, beneficiary);
// set receivedAmount to afterBalance - beforeBalance
receivedAmount = destToken.getBalance(beneficiary) - beforeBalance;
// Check if swap succeeded
if (receivedAmount < toAmount) {
revert InsufficientReturnAmount();
}
}
// Return spentAmount and receivedAmount
return (fromAmount, receivedAmount);
} else {
// swapExactAmountOut
// Unwrap WETH if needed
if (wrap == 2) {
// Execute tryBatchFillOrderMakerAmount
AUGUSTUS_RFQ.tryBatchFillOrderMakerAmount(orders, toAmount, address(this));
// Check remaining WETH balance
receivedAmount = IERC20(WETH).getBalance(address(this));
// Unwrap WETH
WETH.withdraw(--receivedAmount);
// Transfer ETH to beneficiary
ERC20Utils.ETH.safeTransfer(beneficiary, receivedAmount);
// Set toAmount to receivedAmount
toAmount = receivedAmount;
} else {
// Execute tryBatchFillOrderMakerAmount
AUGUSTUS_RFQ.tryBatchFillOrderMakerAmount(orders, toAmount, beneficiary);
}
// Check remaining amount
uint256 remainingAmount = srcToken.getBalance(address(this));
// Send remaining srcToken to msg.sender
if (remainingAmount > 1) {
// If srcToken was ETH
if (wrap == 1) {
// Unwrap WETH
WETH.withdraw(--remainingAmount);
// Transfer ETH to msg.sender
ERC20Utils.ETH.safeTransfer(msg.sender, remainingAmount);
} else {
// Transfer remaining srcToken to msg.sender
srcToken.safeTransfer(msg.sender, --remainingAmount);
}
}
// Return spentAmount and receivedAmount
return (fromAmount - remainingAmount, toAmount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IAugustusRFQ } from "../interfaces/IAugustusRFQ.sol";
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
// Libraries
import { ERC20Utils } from "../libraries/ERC20Utils.sol";
/// @title AugustusRFQUtils
/// @notice A contract containing common utilities for AugustusRFQ swaps
contract AugustusRFQUtils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using ERC20Utils for IERC20;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev Emitted when the msg.sender is not authorized to be the taker
error UnauthorizedUser();
/// @dev Emitted when the orders length is 0
error InvalidOrdersLength();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev AugustusRFQ address
IAugustusRFQ public immutable AUGUSTUS_RFQ; // solhint-disable-line var-name-mixedcase
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _augustusRFQ) {
AUGUSTUS_RFQ = IAugustusRFQ(_augustusRFQ);
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Check if the msg.sender is authorized to be the taker
function _checkAuthorization(uint256 nonceAndMeta) internal view {
// solhint-disable-next-line no-inline-assembly
assembly {
// Parse nonceAndMeta
if xor(and(nonceAndMeta, 0xffffffffffffffffffffffffffffffffffffffff), 0) {
// If the taker is not 0, we check if the msg.sender is authorized
if xor(and(nonceAndMeta, 0xffffffffffffffffffffffffffffffffffffffff), caller()) {
// The taker does not match the originalSender, revert
mstore(0, 0x02a43f8b00000000000000000000000000000000000000000000000000000000) // function
// selector for error UnauthorizedUser();
revert(0, 4)
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Contracts
import { AugustusFees } from "../fees/AugustusFees.sol";
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
// Utils
import { Permit2Utils } from "./Permit2Utils.sol";
import { PauseUtils } from "./PauseUtils.sol";
/// @title BalancerV2Utils
/// @notice A contract containing common utilities for BalancerV2 swaps
abstract contract BalancerV2Utils is AugustusFees, Permit2Utils, PauseUtils {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev Emitted when the passed selector is invalid
error InvalidSelector();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev BalancerV2 vault address
address payable public immutable BALANCER_VAULT; // solhint-disable-line var-name-mixedcase
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address payable _balancerVault) {
BALANCER_VAULT = _balancerVault;
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Decode srcToken, destToken from balancerData, beneficiary and approve flag from beneficiaryAndApproveFlag
function _decodeBalancerV2Params(
uint256 beneficiaryAndApproveFlag,
bytes calldata balancerData
)
internal
pure
returns (IERC20 srcToken, IERC20 destToken, address payable beneficiary, bool approve)
{
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Parse beneficiaryAndApproveFlag
beneficiary := and(beneficiaryAndApproveFlag, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
approve := shr(255, beneficiaryAndApproveFlag)
// Load calldata without selector
let callDataWithoutSelector := add(4, balancerData.offset)
// Check selector
switch calldataload(balancerData.offset)
// If the selector is for swap(tuple singleSwap,tuple funds,uint256 limit,uint256 deadline)
case 0x52bbbe2900000000000000000000000000000000000000000000000000000000 {
// Load srcToken from singleSswap.assetIn
srcToken := calldataload(add(callDataWithoutSelector, 288))
// Load destToken from singleSswap.assetOut
destToken := calldataload(add(callDataWithoutSelector, 320))
}
// If the selector is for batchSwap(uint8 kind,tuple[] swaps,address[] assets,tuple funds,int256[]
// limits,uint256 deadline)
case 0x945bcec900000000000000000000000000000000000000000000000000000000 {
// Load assetOffset from balancerData
let assetsOffset := calldataload(add(callDataWithoutSelector, 64))
// Load assetCount at assetOffset
let assetsCount := calldataload(add(callDataWithoutSelector, assetsOffset))
// Get swapExactAmountIn type from first 32 bytes of balancerData
let swapType := calldataload(callDataWithoutSelector)
// Set fromAmount, srcToken, toAmount and destToken based on swapType
switch eq(swapType, 1)
case 1 {
// Load srcToken as the last asset in balancerData.assets
srcToken := calldataload(add(callDataWithoutSelector, add(assetsOffset, mul(assetsCount, 32))))
// Load destToken as the first asset in balancerData.assets
destToken := calldataload(add(callDataWithoutSelector, add(assetsOffset, 32)))
}
default {
// Load srcToken as the first asset in balancerData.assets
srcToken := calldataload(add(callDataWithoutSelector, add(assetsOffset, 32)))
// Load destToken as the last asset in balancerData.assets
destToken := calldataload(add(callDataWithoutSelector, add(assetsOffset, mul(assetsCount, 32))))
}
}
default {
// If the selector is invalid, revert
mstore(0, 0x7352d91c00000000000000000000000000000000000000000000000000000000) // store the
// selector for error InvalidSelector();
revert(0, 4)
}
// Balancer users 0x0 as ETH address so we need to convert it
if eq(srcToken, 0) { srcToken := 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE }
if eq(destToken, 0) { destToken := 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE }
}
return (srcToken, destToken, beneficiary, approve);
}
/// @dev Call balancerVault with data
function _callBalancerV2(bytes calldata balancerData) internal {
address payable targetAddress = BALANCER_VAULT;
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Load free memory pointer
let ptr := mload(64)
// Copy the balancerData to memory
calldatacopy(ptr, balancerData.offset, balancerData.length)
// Execute the call on balancerVault
if iszero(call(gas(), targetAddress, callvalue(), ptr, balancerData.length, 0, 0)) {
returndatacopy(ptr, 0, returndatasize()) // copy the revert data to memory
revert(ptr, returndatasize()) // revert with the revert data
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Contracts
import { AugustusFees } from "../fees/AugustusFees.sol";
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
// Utils
import { WETHUtils } from "./WETHUtils.sol";
import { Permit2Utils } from "./Permit2Utils.sol";
import { PauseUtils } from "./PauseUtils.sol";
/// @title UniswapV2Utils
/// @notice A contract containing common utilities for UniswapV2 swaps
abstract contract UniswapV2Utils is AugustusFees, WETHUtils, Permit2Utils, PauseUtils {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Used to caluclate pool address
uint256 public immutable UNISWAP_V2_POOL_INIT_CODE_HASH;
/// @dev Right padded FF + UniswapV2Factory address
uint256 public immutable UNISWAP_V2_FACTORY_AND_FF;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(uint256 _uniswapV2FactoryAndFF, uint256 _uniswapV2PoolInitCodeHash) {
UNISWAP_V2_FACTORY_AND_FF = _uniswapV2FactoryAndFF;
UNISWAP_V2_POOL_INIT_CODE_HASH = _uniswapV2PoolInitCodeHash;
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Loops through UniswapV2 pools in backword direction and swaps exact amount out
function _callUniswapV2PoolsSwapExactOut(uint256 amountOut, IERC20 srcToken, bytes calldata pools) internal {
uint256 uniswapV2FactoryAndFF = UNISWAP_V2_FACTORY_AND_FF;
uint256 uniswapV2PoolInitCodeHash = UNISWAP_V2_POOL_INIT_CODE_HASH;
// solhint-disable-next-line no-inline-assembly
assembly {
function calculatePoolAddress(
poolMemoryPtr, poolCalldataPtr, _uniswapV2FactoryAndFF, _uniswapV2PoolInitCodeHash
) {
// Calculate the pool address
// We can do this by first calling the keccak256 function on the passed pool values and then
// calculating keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encodePacked(token0, token1)), POOL_INIT_CODE_HASH));
// The first 20 bytes of the computed address are the pool address
// Store 0xff + factory address (right padded)
mstore(poolMemoryPtr, _uniswapV2FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V2_FACTORY_AND_FF SIZE)
let token0ptr := add(poolMemoryPtr, 21)
// Copy pool data (skip last bit) to free memory pointer + 21 bytes (UNISWAP_V2_FACTORY_AND_FF SIZE)
calldatacopy(token0ptr, poolCalldataPtr, 40)
// Calculate keccak256(abi.encode(address(token0), address(token1))
mstore(token0ptr, keccak256(token0ptr, 40))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), _uniswapV2PoolInitCodeHash)
// Calculate address(keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0, token1), POOL_INIT_CODE_HASH)));
mstore(poolMemoryPtr, and(keccak256(poolMemoryPtr, 85), 0xffffffffffffffffffffffffffffffffffffffff)) // 21
// + 32 + 32
}
// Calculate pool count
let poolCount := div(pools.length, 64)
// Initilize memory pointers
let amounts := mload(64) // pointer for amounts array
let poolAddresses := add(amounts, add(mul(poolCount, 32), 32)) // pointer for pools array
let emptyPtr := add(poolAddresses, mul(poolCount, 32)) // pointer for empty memory
// Initialize fromAmount
let fromAmount := 0
// Set the final amount in the amounts array to amountOut
mstore(add(amounts, mul(poolCount, 0x20)), amountOut)
//---------------------------------//
// Calculate Pool Addresses and Amounts
//---------------------------------//
// Calculate pool addresses
for { let i := 0 } lt(i, poolCount) { i := add(i, 1) } {
calculatePoolAddress(
add(poolAddresses, mul(i, 32)),
add(pools.offset, mul(i, 64)),
uniswapV2FactoryAndFF,
uniswapV2PoolInitCodeHash
)
}
// Rerverse loop through pools and calculate amounts
for { let i := poolCount } gt(i, 0) { i := sub(i, 1) } {
// Use previous pool data to calculate amount in
let indexSub1 := sub(i, 1)
// Get pool address
let poolAddress := mload(add(poolAddresses, mul(indexSub1, 32)))
// Get direction
let direction := and(1, calldataload(add(add(pools.offset, mul(indexSub1, 64)), 32)))
// Get amount
let amount := mload(add(amounts, mul(i, 32)))
//---------------------------------//
// Calculate Amount In
//---------------------------------//
//---------------------------------//
// Get Reserves
//---------------------------------//
// Store the selector
mstore(emptyPtr, 0x0902f1ac00000000000000000000000000000000000000000000000000000000) // 'getReserves()'
// selector
// Perform the external 'getReserves' call - outputs directly to ptr
if iszero(staticcall(gas(), poolAddress, emptyPtr, 4, emptyPtr, 64)) {
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is true, getReserves returns (reserve0, reserve1)
// If direction is false, getReserves returns (reserve1, reserve0) -> swap the values
// Load the reserve0 value returned by the 'getReserves' call.
let reserve1 := mload(emptyPtr)
// Load the reserve1 value returned by the 'getReserves' call.
let reserve0 := mload(add(emptyPtr, 32))
// Check if direction is true
if direction {
// swap reserve0 and reserve1
let temp := reserve0
reserve0 := reserve1
reserve1 := temp
}
//---------------------------------//
// Calculate numerator = reserve0 * amountOut * 10000
let numerator := mul(mul(reserve0, amount), 10000)
// Calculate denominator = (reserve1 - amountOut) * 9970
let denominator := mul(sub(reserve1, amount), 9970)
// Calculate amountIn = numerator / denominator + 1
fromAmount := add(div(numerator, denominator), 1)
// Store amountIn for the previous pool
mstore(add(amounts, mul(indexSub1, 32)), fromAmount)
}
//---------------------------------//
// Initialize variables
let poolAddress := 0
let nextPoolAddress := 0
//---------------------------------//
// Loop Swap Through Pools
//---------------------------------//
// Loop for each pool
for { let i := 0 } lt(i, poolCount) { i := add(i, 1) } {
// Check if it is the first pool
if iszero(poolAddress) {
// If it is the first pool, we need to transfer amount of srcToken to poolAddress
// Load first pool address
poolAddress := mload(poolAddresses)
//---------------------------------//
// Transfer amount of srcToken to poolAddress
//---------------------------------//
// Transfer fromAmount of srcToken to poolAddress
mstore(emptyPtr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (function transfer(address recipient, uint256 amount))
mstore(add(emptyPtr, 4), poolAddress) // store the recipient
mstore(add(emptyPtr, 36), fromAmount) // store the amount
pop(call(gas(), srcToken, 0, emptyPtr, 68, 0, 32)) // call transfer
//---------------------------------//
}
// Adjust toAddress depending on if it is the last pool in the array
let toAddress := address()
// Check if it is not the last pool
if lt(add(i, 1), poolCount) {
// Load next pool address
nextPoolAddress := mload(add(poolAddresses, mul(add(i, 1), 32)))
// Adjust toAddress to next pool address
toAddress := nextPoolAddress
}
// Check direction
let direction := and(1, calldataload(add(add(pools.offset, mul(i, 64)), 32)))
// if direction is 1, amount0out is 0 and amount1out is amount[i+1]
// if direction is 0, amount0out is amount[i+1] and amount1out is 0
// Load amount[i+1]
let amount := mload(add(amounts, mul(add(i, 1), 32)))
// Initialize amount0Out and amount1Out
let amount0Out := amount
let amount1Out := 0
// Check if direction is true
if direction {
// swap amount0Out and amount1Out
let temp := amount0Out
amount0Out := amount1Out
amount1Out := temp
}
//---------------------------------//
// Perform Swap
//---------------------------------//
// Load the 'swap' selector, amount0Out, amount1Out, toAddress and data("") into memory.
mstore(emptyPtr, 0x022c0d9f00000000000000000000000000000000000000000000000000000000)
// 'swap()' selector
mstore(add(emptyPtr, 4), amount0Out) // amount0Out
mstore(add(emptyPtr, 36), amount1Out) // amount1Out
mstore(add(emptyPtr, 68), toAddress) // toAddress
mstore(add(emptyPtr, 100), 0x80) // data length
mstore(add(emptyPtr, 132), 0) // data
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, emptyPtr, 164, 0, 64)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
//---------------------------------//
// Set poolAddress to nextPoolAddress
poolAddress := nextPoolAddress
}
//---------------------------------//
}
}
/// @dev Loops through UniswapV2 pools and swaps exact amount in
function _callUniswapV2PoolsSwapExactIn(
uint256 fromAmount,
IERC20 srcToken,
bytes calldata pools,
address payer,
bytes calldata permit2
)
internal
{
uint256 uniswapV2FactoryAndFF = UNISWAP_V2_FACTORY_AND_FF;
uint256 uniswapV2PoolInitCodeHash = UNISWAP_V2_POOL_INIT_CODE_HASH;
address permit2Address = PERMIT2;
// solhint-disable-next-line no-inline-assembly
assembly {
//---------------------------------//
// Loop Swap Through Pools
//---------------------------------//
// Calculate pool count
let poolCount := div(pools.length, 64)
// Initialize variables
let p := 0
let poolAddress := 0
let nextPoolAddress := 0
let direction := 0
// Loop for each pool
for { let i := 0 } lt(i, poolCount) { i := add(i, 1) } {
// Check if it is the first pool
if iszero(p) {
//---------------------------------//
// Calculate Pool Address
//---------------------------------//
// Calculate the pool address
// We can do this by first calling the keccak256 function on the passed pool values and then
// calculating keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encodePacked(token0,token1)), POOL_INIT_CODE_HASH));
// The first 20 bytes of the computed address are the pool address
// Get free memory pointer
let ptr := mload(64)
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV2FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V2_FACTORY_AND_FF SIZE)
let token0ptr := add(ptr, 21)
// Copy pool data (skip last bit) to free memory pointer + 21 bytes (UNISWAP_V2_FACTORY_AND_FF
// SIZE)
calldatacopy(token0ptr, pools.offset, 40)
// Calculate keccak256(abi.encodePacked(address(token0), address(token1))
mstore(token0ptr, keccak256(token0ptr, 40))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), uniswapV2PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Load pool
p := mload(ptr)
// Get the first 20 bytes of the computed address
poolAddress := and(p, 0xffffffffffffffffffffffffffffffffffffffff)
//---------------------------------//
//---------------------------------//
// Transfer fromAmount of srcToken to poolAddress
//---------------------------------//
switch eq(payer, address())
// if payer is this contract, transfer fromAmount of srcToken to poolAddress
case 1 {
// Transfer fromAmount of srcToken to poolAddress
mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (function transfer(address recipient, uint256 amount))
mstore(add(ptr, 4), poolAddress) // store the recipient
mstore(add(ptr, 36), fromAmount) // store the amount
pop(call(gas(), srcToken, 0, ptr, 68, 0, 32)) // call transfer
}
// othwerwise transferFrom fromAmount of srcToken to poolAddress from payer
default {
switch gt(permit2.length, 256)
case 0 {
// Transfer fromAmount of srcToken to poolAddress
mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // store
// the selector
// (function transferFrom(address sender, address recipient,
// uint256 amount))
mstore(add(ptr, 4), payer) // store the sender
mstore(add(ptr, 36), poolAddress) // store the recipient
mstore(add(ptr, 68), fromAmount) // store the amount
pop(call(gas(), srcToken, 0, ptr, 100, 0, 32)) // call transferFrom
}
default {
// Otherwise Permit2.permitTransferFrom
// Store function selector
mstore(ptr, 0x30f28b7a00000000000000000000000000000000000000000000000000000000)
// permitTransferFrom()
calldatacopy(add(ptr, 4), permit2.offset, permit2.length) // Copy data to memory
mstore(add(ptr, 132), poolAddress) // Store recipient
mstore(add(ptr, 164), fromAmount) // Store amount
mstore(add(ptr, 196), payer) // Store payer
// Call permit2.permitTransferFrom and revert if call failed
if iszero(call(gas(), permit2Address, 0, ptr, add(permit2.length, 4), 0, 0)) {
mstore(0, 0x6b836e6b00000000000000000000000000000000000000000000000000000000) // Store
// error selector
// error Permit2Failed()
revert(0, 4)
}
}
}
//---------------------------------//
}
// Direction is the first bit of the pool data
direction := and(1, calldataload(add(add(pools.offset, mul(i, 64)), 32)))
//---------------------------------//
// Calculate Amount Out
//---------------------------------//
//---------------------------------//
// Get Reserves
//---------------------------------//
// Get free memory pointer
let ptr := mload(64)
// Store the selector
mstore(ptr, 0x0902f1ac00000000000000000000000000000000000000000000000000000000) // 'getReserves()'
// selector
// Perform the external 'getReserves' call - outputs directly to ptr
if iszero(staticcall(gas(), poolAddress, ptr, 4, ptr, 64)) {
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is true, getReserves returns (reserve0, reserve1)
// If direction is false, getReserves returns (reserve1, reserve0) -> swap the values
// Load the reserve0 value returned by the 'getReserves' call.
let reserve1 := mload(ptr)
// Load the reserve1 value returned by the 'getReserves' call.
let reserve0 := mload(add(ptr, 32))
// Check if direction is true
if direction {
// swap reserve0 and reserve1
let temp := reserve0
reserve0 := reserve1
reserve1 := temp
}
//---------------------------------//
// Calculate amount based on fee
let amountWithFee := mul(fromAmount, 9970)
// Calculate numerator = amountWithFee * reserve1
let numerator := mul(amountWithFee, reserve1)
// Calculate denominator = reserve0 * 10000 + amountWithFee
let denominator := add(mul(reserve0, 10000), amountWithFee)
// Calculate amountOut = numerator / denominator
let amountOut := div(numerator, denominator)
fromAmount := amountOut
// if direction is true, amount0Out is 0 and amount1Out is fromAmount,
// otherwise amount0Out is fromAmount and amount1Out is 0
let amount0Out := fromAmount
let amount1Out := 0
// swap amount0Out and amount1Out if direction is false
if direction {
amount0Out := 0
amount1Out := fromAmount
}
//---------------------------------//
// Adjust toAddress depending on if it is the last pool in the array
let toAddress := address()
// Check if it is not the last pool
if lt(add(i, 1), poolCount) {
//---------------------------------//
// Calculate Next Pool Address
//---------------------------------//
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV2FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V2_FACTORY_AND_FF SIZE)
let token0ptr := add(ptr, 21)
// Copy next pool data to free memory pointer + 21 bytes (UNISWAP_V2_FACTORY_AND_FF SIZE)
calldatacopy(token0ptr, add(pools.offset, mul(add(i, 1), 64)), 40)
// Calculate keccak256(abi.encodePacked(address(token0), address(token1))
mstore(token0ptr, keccak256(token0ptr, 40))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), uniswapV2PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Load pool
p := mload(ptr)
// Get the first 20 bytes of the computed address
nextPoolAddress := and(p, 0xffffffffffffffffffffffffffffffffffffffff)
// Adjust toAddress to next pool address
toAddress := nextPoolAddress
//---------------------------------//
}
//---------------------------------//
// Perform Swap
//---------------------------------//
// Load the 'swap' selector, amount0Out, amount1Out, toAddress and data("") into memory.
mstore(ptr, 0x022c0d9f00000000000000000000000000000000000000000000000000000000)
// 'swap()' selector
mstore(add(ptr, 4), amount0Out) // amount0Out
mstore(add(ptr, 36), amount1Out) // amount1Out
mstore(add(ptr, 68), toAddress) // toAddress
mstore(add(ptr, 100), 0x80) // data length
mstore(add(ptr, 132), 0) // data
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, ptr, 164, 0, 64)) {
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
//---------------------------------//
// Set poolAddress to nextPoolAddress
poolAddress := nextPoolAddress
}
//---------------------------------//
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Contracts
import { AugustusFees } from "../fees/AugustusFees.sol";
// Interfaces
import { IUniswapV3SwapCallback } from "../interfaces/IUniswapV3SwapCallback.sol";
// Libraries
import { SafeCastLib } from "@solady/utils/SafeCastLib.sol";
// Utils
import { WETHUtils } from "./WETHUtils.sol";
import { Permit2Utils } from "./Permit2Utils.sol";
import { PauseUtils } from "./PauseUtils.sol";
/// @title UniswapV3Utils
/// @notice A contract containing common utilities for UniswapV3 swaps
abstract contract UniswapV3Utils is IUniswapV3SwapCallback, AugustusFees, WETHUtils, Permit2Utils, PauseUtils {
/*//////////////////////////////////////////////////////////////
LIBRARIES
//////////////////////////////////////////////////////////////*/
using SafeCastLib for int256;
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Error emitted if the caller is not a Uniswap V3 pool
error InvalidCaller();
/// @notice Error emitted if the transfer of tokens to the pool inside the callback failed
error CallbackTransferFailed();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Used to caluclate pool address
uint256 public immutable UNISWAP_V3_POOL_INIT_CODE_HASH;
/// @dev Right padded FF + UniswapV3Factory address
uint256 public immutable UNISWAP_V3_FACTORY_AND_FF;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
uint256 private constant UNISWAP_V3_MIN_SQRT = 4_295_128_740;
uint256 private constant UNISWAP_V3_MAX_SQRT = 1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_341;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(uint256 _uniswapV3FactoryAndFF, uint256 _uniswapV3PoolInitCodeHash) {
UNISWAP_V3_FACTORY_AND_FF = _uniswapV3FactoryAndFF;
UNISWAP_V3_POOL_INIT_CODE_HASH = _uniswapV3PoolInitCodeHash;
}
/*//////////////////////////////////////////////////////////////
EXTERNAL
//////////////////////////////////////////////////////////////*/
// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
)
external
whenNotPaused
{
// Initialize variables
uint256 uniswapV3FactoryAndFF = UNISWAP_V3_FACTORY_AND_FF;
uint256 uniswapV3PoolInitCodeHash = UNISWAP_V3_POOL_INIT_CODE_HASH;
address permit2Address = PERMIT2;
address poolAddress;
// 160 (single pool data) + 352 (permit2 length)
bool isPermit2 = data.length == 512;
// Check if the caller is a UniswapV3Pool deployed by the canonical UniswapV3Factory
//solhint-disable-next-line no-inline-assembly
assembly {
// Pool address
poolAddress := caller()
// Get free memory pointer
let ptr := mload(64)
// We need make sure the caller is a UniswapV3Pool deployed by the canonical UniswapV3Factory
// 1. Prepare data for calculating the pool address
// Store ff+factory address, Load token0, token1, fee from bytes calldata and store pool init code hash
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV3FactoryAndFF)
// Store data offset + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE)
let token0Offset := add(ptr, 21)
// Copy token0, token1, fee to free memory pointer + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE) + 1 byte
// (direction)
calldatacopy(add(token0Offset, 1), add(data.offset, 65), 95)
// 2. Calculate the pool address
// We can do this by first calling the keccak256 function on the fetched values and then
// calculating keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
// The first 20 bytes of the computed address are the pool address
// Calculate keccak256(abi.encode(address(token0), address(token1), fee))
mstore(token0Offset, keccak256(token0Offset, 96))
// Store POOL_INIT_CODE_HASH
mstore(add(token0Offset, 32), uniswapV3PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address), keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Get the first 20 bytes of the computed address
let computedAddress := and(mload(ptr), 0xffffffffffffffffffffffffffffffffffffffff)
// Check if the caller matches the computed address (and revert if not)
if xor(poolAddress, computedAddress) {
mstore(0, 0x48f5c3ed00000000000000000000000000000000000000000000000000000000) // store the selector
// (error InvalidCaller())
revert(0, 4) // revert with error selector
}
}
// Check if data length is greater than 160 bytes (1 pool)
// If the data length is greater than 160 bytes, we know that we are executing a multi-hop swapExactAmountOut
// by recursively calling swapExactAmountOut on the next pool, until we reach the last pool in the data and
// then we will transfer the tokens to the pool
if (data.length > 160 && !isPermit2) {
// Initialize recursive variables
address payer;
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy payer address from calldata
payer := calldataload(164)
}
// Recursive call swapExactAmountOut
_callUniswapV3PoolsSwapExactAmountOut(amount0Delta > 0 ? -amount0Delta : -amount1Delta, data, payer);
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
// Token to send to the pool
let token
// Amount to send to the pool
let amount
// Get free memory pointer
let ptr := mload(64)
// If the caller is the computed address, then we can safely assume that the caller is a UniswapV3Pool
// deployed by the canonical UniswapV3Factory
// 3. Transfer amount to the pool
// Check if amount0Delta or amount1Delta is positive and which token we need to send to the pool
if sgt(amount0Delta, 0) {
// If amount0Delta is positive, we need to send amount0Delta token0 to the pool
token := and(calldataload(add(data.offset, 64)), 0xffffffffffffffffffffffffffffffffffffffff)
amount := amount0Delta
}
if sgt(amount1Delta, 0) {
// If amount1Delta is positive, we need to send amount1Delta token1 to the pool
token := calldataload(add(data.offset, 96))
amount := amount1Delta
}
// Based on the data passed to the callback, we know the fromAddress that will pay for the
// swap, if it is this contract, we will execute the transfer() function,
// otherwise, we will execute transferFrom()
// Check if fromAddress is this contract
let fromAddress := calldataload(164)
switch eq(fromAddress, address())
// If fromAddress is this contract, execute transfer()
case 1 {
// Prepare external call data
mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (function transfer(address recipient, uint256 amount))
mstore(add(ptr, 4), poolAddress) // store the recipient
mstore(add(ptr, 36), amount) // store the amount
let success := call(gas(), token, 0, ptr, 68, 0, 32) // call transfer
if success {
switch returndatasize()
// check the return data size
case 0 { success := gt(extcodesize(token), 0) }
default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
}
if iszero(success) {
mstore(0, 0x1bbb4abe00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (error CallbackTransferFailed())
revert(0, 4) // revert with error selector
}
}
// If fromAddress is not this contract, execute transferFrom() or permitTransferFrom()
default {
switch isPermit2
// If permit2 is not present, execute transferFrom()
case 0 {
mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (function transferFrom(address sender, address recipient,
// uint256 amount))
mstore(add(ptr, 4), fromAddress) // store the sender
mstore(add(ptr, 36), poolAddress) // store the recipient
mstore(add(ptr, 68), amount) // store the amount
let success := call(gas(), token, 0, ptr, 100, 0, 32) // call transferFrom
if success {
switch returndatasize()
// check the return data size
case 0 { success := gt(extcodesize(token), 0) }
default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
}
if iszero(success) {
mstore(0, 0x1bbb4abe00000000000000000000000000000000000000000000000000000000) // store the
// selector
// (error CallbackTransferFailed())
revert(0, 4) // revert with error selector
}
}
// If permit2 is present, execute permitTransferFrom()
default {
// Otherwise Permit2.permitTransferFrom
// Store function selector
mstore(ptr, 0x30f28b7a00000000000000000000000000000000000000000000000000000000)
// permitTransferFrom()
calldatacopy(add(ptr, 4), 292, 352) // Copy data to memory
mstore(add(ptr, 132), poolAddress) // Store pool address as recipient
mstore(add(ptr, 164), amount) // Store amount as amount
mstore(add(ptr, 196), fromAddress) // Store payer
// Call permit2.permitTransferFrom and revert if call failed
if iszero(call(gas(), permit2Address, 0, ptr, 356, 0, 0)) {
mstore(0, 0x6b836e6b00000000000000000000000000000000000000000000000000000000) // Store
// error selector
// error Permit2Failed()
revert(0, 4)
}
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Loops through pools and performs swaps
function _callUniswapV3PoolsSwapExactAmountIn(
int256 fromAmount,
bytes calldata pools,
address fromAddress,
bytes calldata permit2
)
internal
returns (uint256 receivedAmount)
{
uint256 uniswapV3FactoryAndFF = UNISWAP_V3_FACTORY_AND_FF;
uint256 uniswapV3PoolInitCodeHash = UNISWAP_V3_POOL_INIT_CODE_HASH;
// solhint-disable-next-line no-inline-assembly
assembly {
//---------------------------------//
// Loop Swap Through Pools
//---------------------------------//
// Calculate pool count
let poolCount := div(pools.length, 96)
// Initialize variables
let p := 0
let poolAddress := 0
let nextPoolAddress := 0
let direction := 0
let isPermit2 := gt(permit2.length, 256)
// Get free memory pointer
let ptr := mload(64)
// Loop through pools
for { let i := 0 } lt(i, poolCount) { i := add(i, 1) } {
// Check if it is the first pool
if iszero(p) {
//---------------------------------//
// Calculate Pool Address
//---------------------------------//
// Calculate the pool address
// We can do this by first calling the keccak256 function on the passed pool values and then
// calculating keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
// The first 20 bytes of the computed address are the pool address
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV3FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE)
let token0ptr := add(ptr, 21)
// Copy pool data (skip first byte) to free memory pointer + 21 bytes (UNISWAP_V3_FACTORY_AND_FF
// SIZE)
calldatacopy(add(token0ptr, 1), add(pools.offset, 1), 95)
// Calculate keccak256(abi.encode(address(token0), address(token1), fee))
mstore(token0ptr, keccak256(token0ptr, 96))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), uniswapV3PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Load pool
p := mload(ptr)
// Get the first 20 bytes of the computed address
poolAddress := and(p, 0xffffffffffffffffffffffffffffffffffffffff)
//---------------------------------//
}
// Direction is the first bit of the pool data
direction := shr(255, calldataload(add(pools.offset, mul(i, 96))))
// Check if it is not the last pool
if lt(add(i, 1), poolCount) {
//---------------------------------//
// Calculate Next Pool Address
//---------------------------------//
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV3FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE)
let token0ptr := add(ptr, 21)
// Copy next pool data to free memory pointer + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE)
calldatacopy(add(token0ptr, 1), add(add(pools.offset, 1), mul(add(i, 1), 96)), 95)
// Calculate keccak256(abi.encode(address(token0), address(token1), fee))
mstore(token0ptr, keccak256(token0ptr, 96))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), uniswapV3PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Load pool
p := mload(ptr)
// Get the first 20 bytes of the computed address
nextPoolAddress := and(p, 0xffffffffffffffffffffffffffffffffffffffff)
//---------------------------------//
}
// Adjust fromAddress and fromAmount if it's not the first pool
if gt(i, 0) { fromAddress := address() }
//---------------------------------//
// Perform Swap
//---------------------------------//
//---------------------------------//
// Return based on direction
//---------------------------------//
// Initialize data length
let dataLength := 0xa0
// Initialize total data length
let totalDataLength := 356
// If permit2 is present include permit2 data length in total data length
if eq(isPermit2, 1) {
totalDataLength := add(totalDataLength, permit2.length)
dataLength := add(dataLength, permit2.length)
}
// Return amount0 or amount1 depending on direction
switch direction
case 0 {
// Prepare external call data
// Store swap selector (0x128acb08)
mstore(ptr, 0x128acb0800000000000000000000000000000000000000000000000000000000)
// Store toAddress
mstore(add(ptr, 4), address())
// Store direction
mstore(add(ptr, 36), 0)
// Store fromAmount
mstore(add(ptr, 68), fromAmount)
// Store sqrtPriceLimitX96
mstore(add(ptr, 100), UNISWAP_V3_MAX_SQRT)
// Store data offset
mstore(add(ptr, 132), 0xa0)
/// Store data length
mstore(add(ptr, 164), dataLength)
// Store fromAddress
mstore(add(ptr, 228), fromAddress)
// Store token0, token1, fee
calldatacopy(add(ptr, 260), add(pools.offset, mul(i, 96)), 96)
// If permit2 is present, store permit2 data
if eq(isPermit2, 1) {
// Store permit2 data
calldatacopy(add(ptr, 356), permit2.offset, permit2.length)
}
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, ptr, totalDataLength, ptr, 32)) {
// store return value directly to free memory pointer
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is 0, return amount0
fromAmount := mload(ptr)
}
default {
// Prepare external call data
// Store swap selector (0x128acb08)
mstore(ptr, 0x128acb0800000000000000000000000000000000000000000000000000000000)
// Store toAddress
mstore(add(ptr, 4), address())
// Store direction
mstore(add(ptr, 36), 1)
// Store fromAmount
mstore(add(ptr, 68), fromAmount)
// Store sqrtPriceLimitX96
mstore(add(ptr, 100), UNISWAP_V3_MIN_SQRT)
// Store data offset
mstore(add(ptr, 132), 0xa0)
/// Store data length
mstore(add(ptr, 164), dataLength)
// Store fromAddress
mstore(add(ptr, 228), fromAddress)
// Store token0, token1, fee
calldatacopy(add(ptr, 260), add(pools.offset, mul(i, 96)), 96)
// If permit2 is present, store permit2 data
if eq(isPermit2, 1) {
// Store permit2 data
calldatacopy(add(ptr, 356), permit2.offset, permit2.length)
}
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, ptr, totalDataLength, ptr, 64)) {
// store return value directly to free memory pointer
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is 1, return amount1
fromAmount := mload(add(ptr, 32))
}
//---------------------------------//
//---------------------------------//
// The next pool address was already calculated so we can set it as the current pool address for the
// next iteration of the loop
poolAddress := nextPoolAddress
// fromAmount = -fromAmount
fromAmount := sub(0, fromAmount)
}
//---------------------------------//
}
return fromAmount.toUint256();
}
/// @dev Recursively loops through pools and performs swaps
function _callUniswapV3PoolsSwapExactAmountOut(
int256 fromAmount,
bytes calldata pools,
address fromAddress
)
internal
returns (uint256 spentAmount, uint256 receivedAmount)
{
uint256 uniswapV3FactoryAndFF = UNISWAP_V3_FACTORY_AND_FF;
uint256 uniswapV3PoolInitCodeHash = UNISWAP_V3_POOL_INIT_CODE_HASH;
// solhint-disable-next-line no-inline-assembly
assembly {
//---------------------------------//
// Adjust data received from recursive call
//---------------------------------//
// Initialize variables
let poolsStartOffset := pools.offset
let poolsLength := pools.length
let previousPoolAddress := 0
// Check if pools length is not divisible by 96
if gt(mod(pools.length, 96), 0) {
// Check if pools length is greater than 128 bytes (1 pool)
if gt(pools.length, 160) {
// Get the previous pool address from the first 20 bytes of pool data
previousPoolAddress := and(calldataload(pools.offset), 0xffffffffffffffffffffffffffffffffffffffff)
// Relculate the offset to skip data
poolsStartOffset := add(pools.offset, 160)
// Recalculate the length to skip data
poolsLength := sub(pools.length, 160)
}
}
// Get free memory pointer
let ptr := mload(64)
//---------------------------------//
// Calculate Pool Address
//---------------------------------//
// Calculate the pool address
// We can do this by first calling the keccak256 function on the passed pool values and then
// calculating keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
// The first 20 bytes of the computed address are the pool address
// Store 0xff + factory address (right padded)
mstore(ptr, uniswapV3FactoryAndFF)
// Store pools offset + 21 bytes (UNISWAP_V3_FACTORY_AND_FF SIZE)
let token0ptr := add(ptr, 21)
// Copy pool data (skip first byte) to free memory pointer + 21 bytes (UNISWAP_V3_FACTORY_AND_FF
// SIZE)
calldatacopy(add(token0ptr, 1), add(poolsStartOffset, 1), 95)
// Calculate keccak256(abi.encode(address(token0), address(token1), fee))
mstore(token0ptr, keccak256(token0ptr, 96))
// Store POOL_INIT_CODE_HASH
mstore(add(token0ptr, 32), uniswapV3PoolInitCodeHash)
// Calculate keccak256(abi.encodePacked(hex'ff', address(factory_address),
// keccak256(abi.encode(token0,
// token1, fee)), POOL_INIT_CODE_HASH));
mstore(ptr, keccak256(ptr, 85)) // 21 + 32 + 32
// Load pool
let p := mload(ptr)
// Get the first 20 bytes of the computed address
let poolAddress := and(p, 0xffffffffffffffffffffffffffffffffffffffff)
//---------------------------------//
//---------------------------------//
// Adjust toAddress
//---------------------------------//
let toAddress := address()
// If it's not the first entry to recursion, we use the pool address from the previous pool as
// the toAddress
if xor(previousPoolAddress, 0) { toAddress := previousPoolAddress }
//---------------------------------//
// Direction is the first bit of the pool data
let direction := shr(255, calldataload(poolsStartOffset))
//---------------------------------//
// Perform Swap
//---------------------------------//
//---------------------------------//
// Return based on direction
//---------------------------------//
// Return amount0 or amount1 depending on direction
switch direction
case 0 {
// Prepare external call data
// Store swap selector (0x128acb08)
mstore(ptr, 0x128acb0800000000000000000000000000000000000000000000000000000000)
// Store toAddress
mstore(add(ptr, 4), toAddress)
// Store direction
mstore(add(ptr, 36), 0)
// Store fromAmount
mstore(add(ptr, 68), fromAmount)
// Store sqrtPriceLimitX96
mstore(add(ptr, 100), UNISWAP_V3_MAX_SQRT)
// Store data offset
mstore(add(ptr, 132), 0xa0)
/// Store data length
mstore(add(ptr, 164), add(64, poolsLength))
// Store poolAddress
mstore(add(ptr, 196), poolAddress)
// Store fromAddress
mstore(add(ptr, 228), fromAddress)
// Store token0, token1, fee
calldatacopy(add(ptr, 260), poolsStartOffset, poolsLength)
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, ptr, add(poolsLength, 260), ptr, 64)) {
// store return value directly to free memory pointer
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is 0, return amount0 as fromAmount
fromAmount := mload(ptr)
// return amount1 as spentAmount
spentAmount := mload(add(ptr, 32))
}
default {
// Prepare external call data
// Store swap selector (0x128acb08)
mstore(ptr, 0x128acb0800000000000000000000000000000000000000000000000000000000)
// Store toAddress
mstore(add(ptr, 4), toAddress)
// Store direction
mstore(add(ptr, 36), 1)
// Store fromAmount
mstore(add(ptr, 68), fromAmount)
// Store sqrtPriceLimitX96
mstore(add(ptr, 100), UNISWAP_V3_MIN_SQRT)
// Store data offset
mstore(add(ptr, 132), 0xa0)
/// Store data length
mstore(add(ptr, 164), add(64, poolsLength))
// Store poolAddress
mstore(add(ptr, 196), poolAddress)
// Store fromAddress
mstore(add(ptr, 228), fromAddress)
// Store token0, token1, fee
calldatacopy(add(ptr, 260), poolsStartOffset, poolsLength)
// Perform the external 'swap' call
if iszero(call(gas(), poolAddress, 0, ptr, add(poolsLength, 260), ptr, 64)) {
// store return value directly to free memory pointer
// The call failed; we retrieve the exact error message and revert with it
returndatacopy(0, 0, returndatasize()) // Copy the error message to the start of memory
revert(0, returndatasize()) // Revert with the error message
}
// If direction is 1, return amount1 as fromAmount
fromAmount := mload(add(ptr, 32))
// return amount0 as spentAmount
spentAmount := mload(ptr)
}
//---------------------------------//
//---------------------------------//
// fromAmount = -fromAmount
fromAmount := sub(0, fromAmount)
}
return (spentAmount, fromAmount.toUint256());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IWETH } from "../interfaces/IWETH.sol";
/// @title WETHUtils
/// @notice A contract containing common utilities for WETH
abstract contract WETHUtils {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev WETH address
IWETH public immutable WETH;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _weth) {
WETH = IWETH(_weth);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/// @title Permit2Utils
/// @notice A contract containing common utilities for Permit2
abstract contract Permit2Utils {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error Permit2Failed();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Permit2 address
address public immutable PERMIT2; // solhint-disable-line var-name-mixedcase
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _permit2) {
PERMIT2 = _permit2;
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Parses data and executes permit2.permitTransferFrom, reverts if it fails
function permit2TransferFrom(bytes calldata data, address recipient, uint256 amount) internal {
address targetAddress = PERMIT2;
// solhint-disable-next-line no-inline-assembly
assembly {
// Get free memory pointer
let ptr := mload(64)
// Store function selector
mstore(ptr, 0x30f28b7a00000000000000000000000000000000000000000000000000000000) // permitTransferFrom()
// Copy data to memory
calldatacopy(add(ptr, 4), data.offset, data.length)
// Store recipient
mstore(add(ptr, 132), recipient)
// Store amount
mstore(add(ptr, 164), amount)
// Store owner
mstore(add(ptr, 196), caller())
// Call permit2.permitTransferFrom and revert if call failed
if iszero(call(gas(), targetAddress, 0, ptr, add(data.length, 4), 0, 0)) {
mstore(0, 0x6b836e6b00000000000000000000000000000000000000000000000000000000) // Store error selector
// error Permit2Failed()
revert(0, 4)
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (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.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets 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.
*/
function approve(address spender, uint256 value) external returns (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.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { BalancerV2Data } from "../AugustusV6Types.sol";
/// @title IBalancerV2SwapExactAmountIn
/// @notice Interface for executing swapExactAmountIn directly on Balancer V2 pools
interface IBalancerV2SwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountIn on Balancer V2 pools
/// @param balancerData Struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit Permit data for the swap
/// @param data The calldata to execute
/// the first 20 bytes are the beneficiary address and the left most bit is the approve flag
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountInOnBalancerV2(
BalancerV2Data calldata balancerData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata data
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
/// @title ERC20Utils
/// @notice Optimized functions for ERC20 tokens
library ERC20Utils {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error IncorrectEthAmount();
error PermitFailed();
error TransferFromFailed();
error TransferFailed();
error ApprovalFailed();
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
IERC20 internal constant ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/*//////////////////////////////////////////////////////////////
APPROVE
//////////////////////////////////////////////////////////////*/
/// @dev Vendored from Solady by @vectorized - SafeTransferLib.approveWithRetry
/// https://github.com/Vectorized/solady/src/utils/SafeTransferLib.sol#L325
/// Instead of approving a specific amount, this function approves for uint256(-1) (type(uint256).max).
function approve(IERC20 token, address to) internal {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // Store the `amount`
// argument (type(uint256).max).
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // Store
// type(uint256).max for the `amount`.
// Retry the approval, reverting upon failure.
if iszero(
and(
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0, 0x8164f84200000000000000000000000000000000000000000000000000000000)
// store the selector (error ApprovalFailed())
revert(0, 4) // revert with error selector
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/*//////////////////////////////////////////////////////////////
PERMIT
//////////////////////////////////////////////////////////////*/
/// @dev Executes an ERC20 permit and reverts if invalid length is provided
function permit(IERC20 token, bytes calldata data) internal {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// check the permit length
switch data.length
// 32 * 7 = 224 EIP2612 Permit
case 224 {
let x := mload(64) // get the free memory pointer
mstore(x, 0xd505accf00000000000000000000000000000000000000000000000000000000) // store the selector
// function permit(address owner, address spender, uint256
// amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
calldatacopy(add(x, 4), data.offset, 224) // store the args
pop(call(gas(), token, 0, x, 228, 0, 32)) // call ERC20 permit, skip checking return data
}
// 32 * 8 = 256 DAI-Style Permit
case 256 {
let x := mload(64) // get the free memory pointer
mstore(x, 0x8fcbaf0c00000000000000000000000000000000000000000000000000000000) // store the selector
// function permit(address holder, address spender, uint256
// nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)
calldatacopy(add(x, 4), data.offset, 256) // store the args
pop(call(gas(), token, 0, x, 260, 0, 32)) // call ERC20 permit, skip checking return data
}
default {
mstore(0, 0xb78cb0dd00000000000000000000000000000000000000000000000000000000) // store the selector
// (error PermitFailed())
revert(0, 4)
}
}
}
/*//////////////////////////////////////////////////////////////
ETH
//////////////////////////////////////////////////////////////*/
/// @dev Returns 1 if the token is ETH, 0 if not ETH
function isETH(IERC20 token, uint256 amount) internal view returns (uint256 fromETH) {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// If token is ETH
if eq(token, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
// if msg.value is not equal to fromAmount, then revert
if xor(amount, callvalue()) {
mstore(0, 0x8b6ebb4d00000000000000000000000000000000000000000000000000000000) // store the selector
// (error IncorrectEthAmount())
revert(0, 4) // revert with error selector
}
// return 1 if ETH
fromETH := 1
}
// If token is not ETH
if xor(token, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
// if msg.value is not equal to 0, then revert
if gt(callvalue(), 0) {
mstore(0, 0x8b6ebb4d00000000000000000000000000000000000000000000000000000000) // store the selector
// (error IncorrectEthAmount())
revert(0, 4) // revert with error selector
}
}
}
// return 0 if not ETH
}
/*//////////////////////////////////////////////////////////////
TRANSFER
//////////////////////////////////////////////////////////////*/
/// @dev Executes transfer and reverts if it fails, works for both ETH and ERC20 transfers
function safeTransfer(IERC20 token, address recipient, uint256 amount) internal returns (bool success) {
// solhint-disable-next-line no-inline-assembly
assembly {
switch eq(token, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
// ETH
case 1 {
// transfer ETH
// Cap gas at 10000 to avoid reentrancy
success := call(10000, recipient, amount, 0, 0, 0, 0)
}
// ERC20
default {
let x := mload(64) // get the free memory pointer
mstore(x, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // store the selector
// (function transfer(address recipient, uint256 amount))
mstore(add(x, 4), recipient) // store the recipient
mstore(add(x, 36), amount) // store the amount
success := call(gas(), token, 0, x, 68, 0, 32) // call transfer
if success {
switch returndatasize()
// check the return data size
case 0 { success := gt(extcodesize(token), 0) }
default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
}
}
if iszero(success) {
mstore(0, 0x90b8ec1800000000000000000000000000000000000000000000000000000000) // store the selector
// (error TransferFailed())
revert(0, 4) // revert with error selector
}
}
}
/*//////////////////////////////////////////////////////////////
TRANSFER FROM
//////////////////////////////////////////////////////////////*/
/// @dev Executes transferFrom and reverts if it fails
function safeTransferFrom(
IERC20 srcToken,
address sender,
address recipient,
uint256 amount
)
internal
returns (bool success)
{
// solhint-disable-next-line no-inline-assembly
assembly {
let x := mload(64) // get the free memory pointer
mstore(x, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // store the selector
// (function transferFrom(address sender, address recipient,
// uint256 amount))
mstore(add(x, 4), sender) // store the sender
mstore(add(x, 36), recipient) // store the recipient
mstore(add(x, 68), amount) // store the amount
success := call(gas(), srcToken, 0, x, 100, 0, 32) // call transferFrom
if success {
switch returndatasize()
// check the return data size
case 0 { success := gt(extcodesize(srcToken), 0) }
default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
}
if iszero(success) {
mstore(x, 0x7939f42400000000000000000000000000000000000000000000000000000000) // store the selector
// (error TransferFromFailed())
revert(x, 4) // revert with error selector
}
}
}
/*//////////////////////////////////////////////////////////////
BALANCE
//////////////////////////////////////////////////////////////*/
/// @dev Returns the balance of an account, works for both ETH and ERC20 tokens
function getBalance(IERC20 token, address account) internal view returns (uint256 balanceOf) {
// solhint-disable-next-line no-inline-assembly
assembly {
switch eq(token, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
// ETH
case 1 { balanceOf := balance(account) }
// ERC20
default {
let x := mload(64) // get the free memory pointer
mstore(x, 0x70a0823100000000000000000000000000000000000000000000000000000000) // store the selector
// (function balanceOf(address account))
mstore(add(x, 4), account) // store the account
let success := staticcall(gas(), token, x, 36, x, 32) // call balanceOf
if success { balanceOf := mload(x) } // load the balance
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
/*//////////////////////////////////////////////////////////////
GENERIC SWAP DATA
//////////////////////////////////////////////////////////////*/
/// @notice Struct containg data for generic swapExactAmountIn/swapExactAmountOut
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param quotedAmount The quoted expected amount of destToken/srcToken
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiary The address to send the swapped tokens to
struct GenericData {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
/*//////////////////////////////////////////////////////////////
UNISWAPV2
//////////////////////////////////////////////////////////////*/
/// @notice Struct for UniswapV2 swapExactAmountIn/swapExactAmountOut data
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param quotedAmount The quoted expected amount of destToken/srcToken
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiary The address to send the swapped tokens to
/// @param pools data consisting of concatenated token0 and token1 address for each pool with the direction flag being
/// the right most bit of the packed token0-token1 pair bytes used in the path
struct UniswapV2Data {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
bytes pools;
}
/*//////////////////////////////////////////////////////////////
UNISWAPV3
//////////////////////////////////////////////////////////////*/
/// @notice Struct for UniswapV3 swapExactAmountIn/swapExactAmountOut data
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param quotedAmount The quoted expected amount of destToken/srcToken
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiary The address to send the swapped tokens to
/// @param pools data consisting of concatenated token0-
/// token1-fee bytes for each pool used in the path, with the direction flag being the left most bit of token0 in the
/// concatenated bytes
struct UniswapV3Data {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
bytes pools;
}
/*//////////////////////////////////////////////////////////////
CURVE V1
//////////////////////////////////////////////////////////////*/
/// @notice Struct for CurveV1 swapExactAmountIn data
/// @param curveData Packed data for the Curve pool, first 160 bits is the target exchange address,
/// the 161st bit is the approve flag, bits from (162 - 163) are used for the wrap flag,
//// bits from (164 - 165) are used for the swapType flag and the last 91 bits are unused:
/// Approve Flag - a) 0 -> do not approve b) 1 -> approve
/// Wrap Flag - a) 0 -> do not wrap b) 1 -> wrap native & srcToken == eth
/// c) 2 -> unwrap and destToken == eth d) 3 - >srcToken == eth && do not wrap
/// Swap Type Flag - a) 0 -> EXCHANGE b) 1 -> EXCHANGE_UNDERLYING
/// @param curveAssets Packed uint128 index i and uint128 index j of the pool
/// The first 128 bits is the index i and the second 128 bits is the index j
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount that must be recieved
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param quotedAmount The expected amount of destToken to be recieved
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiary The address to send the swapped tokens to
struct CurveV1Data {
uint256 curveData;
uint256 curveAssets;
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
/*//////////////////////////////////////////////////////////////
CURVE V2
//////////////////////////////////////////////////////////////*/
/// @notice Struct for CurveV2 swapExactAmountIn data
/// @param curveData Packed data for the Curve pool, first 160 bits is the target exchange address,
/// the 161st bit is the approve flag, bits from (162 - 163) are used for the wrap flag,
//// bits from (164 - 165) are used for the swapType flag and the last 91 bits are unused
/// Approve Flag - a) 0 -> do not approve b) 1 -> approve
/// Approve Flag - a) 0 -> do not approve b) 1 -> approve
/// Wrap Flag - a) 0 -> do not wrap b) 1 -> wrap native & srcToken == eth
/// c) 2 -> unwrap and destToken == eth d) 3 - >srcToken == eth && do not wrap
/// Swap Type Flag - a) 0 -> EXCHANGE b) 1 -> EXCHANGE_UNDERLYING c) 2 -> EXCHANGE_UNDERLYING_FACTORY_ZAP
/// @param i The index of the srcToken
/// @param j The index of the destToken
/// The first 128 bits is the index i and the second 128 bits is the index j
/// @param poolAddress The address of the CurveV2 pool (only used for EXCHANGE_UNDERLYING_FACTORY_ZAP)
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount that must be recieved
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param quotedAmount The expected amount of destToken to be recieved
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiary The address to send the swapped tokens to
struct CurveV2Data {
uint256 curveData;
uint256 i;
uint256 j;
address poolAddress;
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
address payable beneficiary;
}
/*//////////////////////////////////////////////////////////////
BALANCER V2
//////////////////////////////////////////////////////////////*/
/// @notice Struct for BalancerV2 swapExactAmountIn data
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param quotedAmount The quoted expected amount of destToken/srcToken
/// = quotedAmountOut for swapExactAmountIn and quotedAmountIn for swapExactAmountOut
/// @param metadata Packed uuid and additional metadata
/// @param beneficiaryAndApproveFlag The beneficiary address and approve flag packed into one uint256,
/// the first 20 bytes are the beneficiary address and the left most bit is the approve flag
struct BalancerV2Data {
uint256 fromAmount;
uint256 toAmount;
uint256 quotedAmount;
bytes32 metadata;
uint256 beneficiaryAndApproveFlag;
}
/*//////////////////////////////////////////////////////////////
MAKERPSM
//////////////////////////////////////////////////////////////*/
/// @notice Struct for Maker PSM swapExactAmountIn data
/// @param srcToken The token to swap from
/// @param destToken The token to swap to
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param toll Used to calculate gem amount for the swapExactAmountIn
/// @param to18ConversionFactor Used to calculate gem amount for the swapExactAmountIn
/// @param gemJoinAddress The address of the gemJoin contract
/// @param exchange The address of the exchange contract
/// @param metadata Packed uuid and additional metadata
/// @param beneficiaryDirectionApproveFlag The beneficiary address, swap direction and approve flag packed
/// into one uint256, the first 20 bytes are the beneficiary address, the left most bit is the approve flag and the
/// second left most bit is the swap direction flag, 0 for swapExactAmountIn and 1 for swapExactAmountOut
struct MakerPSMData {
IERC20 srcToken;
IERC20 destToken;
uint256 fromAmount;
uint256 toAmount;
uint256 toll;
uint256 to18ConversionFactor;
address exchange;
address gemJoinAddress;
bytes32 metadata;
uint256 beneficiaryDirectionApproveFlag;
}
/*//////////////////////////////////////////////////////////////
AUGUSTUS RFQ
//////////////////////////////////////////////////////////////*/
/// @notice Order struct for Augustus RFQ
/// @param nonceAndMeta The nonce and meta data packed into one uint256,
/// the first 160 bits is the user address and the last 96 bits is the nonce
/// @param expiry The expiry of the order
/// @param makerAsset The address of the maker asset
/// @param takerAsset The address of the taker asset
/// @param maker The address of the maker
/// @param taker The address of the taker, if the taker is address(0) anyone can take the order
/// @param makerAmount The amount of makerAsset
/// @param takerAmount The amount of takerAsset
struct Order {
uint256 nonceAndMeta;
uint128 expiry;
address makerAsset;
address takerAsset;
address maker;
address taker;
uint256 makerAmount;
uint256 takerAmount;
}
/// @notice Struct containing order info for Augustus RFQ
/// @param order The order struct
/// @param signature The signature for the order
/// @param takerTokenFillAmount The amount of takerToken to fill
/// @param permitTakerAsset The permit data for the taker asset
/// @param permitMakerAsset The permit data for the maker asset
struct OrderInfo {
Order order;
bytes signature;
uint256 takerTokenFillAmount;
bytes permitTakerAsset;
bytes permitMakerAsset;
}
/// @notice Struct containing common data for executing swaps on Augustus RFQ
/// @param fromAmount The amount of srcToken to swap
/// = amountIn for swapExactAmountIn and maxAmountIn for swapExactAmountOut
/// @param toAmount The minimum amount of destToken to receive
/// = minAmountOut for swapExactAmountIn and amountOut for swapExactAmountOut
/// @param wrapApproveDirection The wrap, approve and direction flag packed into one uint8,
/// the first 2 bits is wrap flag (10 for wrap dest, 01 for wrap src, 00 for no wrap), the next bit is the approve flag
/// (1 for approve, 0 for no approve) and the last bit is the direction flag (0 for swapExactAmountIn and 1 for
/// swapExactAmountOut)
/// @param metadata Packed uuid and additional metadata
struct AugustusRFQData {
uint256 fromAmount;
uint256 toAmount;
uint8 wrapApproveDirection;
bytes32 metadata;
address payable beneficiary;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { CurveV1Data } from "../AugustusV6Types.sol";
/// @title ICurveV1SwapExactAmountIn
/// @notice Interface for direct swaps on Curve V1
interface ICurveV1SwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountIn on Curve V1 pools
/// @param curveV1Data Struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit Permit data for the swap
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountInOnCurveV1(
CurveV1Data calldata curveV1Data,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Storage
import { AugustusStorage } from "../storage/AugustusStorage.sol";
/// @title PauseUtils
/// @notice Provides a modifier to check if the contract is paused
abstract contract PauseUtils is AugustusStorage {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Error emitted when the contract is paused
error ContractPaused();
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
// Check if the contract is paused, if it is, revert
modifier whenNotPaused() {
if (paused) {
revert ContractPaused();
}
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { CurveV2Data } from "../AugustusV6Types.sol";
/// @title ICurveV2SwapExactAmountIn
/// @notice Interface for direct swaps on Curve V2
interface ICurveV2SwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountIn on Curve V2 pools
/// @param curveV2Data Struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit Permit data for the swap
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountInOnCurveV2(
CurveV2Data calldata curveV2Data,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { UniswapV2Data } from "../AugustusV6Types.sol";
/// @title IUniswapV2SwapExactAmountIn
/// @notice Interface for direct swaps on Uniswap V2
interface IUniswapV2SwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountIn on Uniswap V2 pools
/// @param uniData struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountInOnUniswapV2(
UniswapV2Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { UniswapV3Data } from "../AugustusV6Types.sol";
/// @title IUniswapV3SwapExactAmountIn
/// @notice Interface for executing direct swapExactAmountIn on Uniswap V3
interface IUniswapV3SwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountIn on Uniswap V3 pools
/// @param uniData struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountInOnUniswapV3(
UniswapV3Data calldata uniData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
library SafeCastLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error Overflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
function toUint16(uint256 x) internal pure returns (uint16) {
if (x >= 1 << 16) _revertOverflow();
return uint16(x);
}
function toUint24(uint256 x) internal pure returns (uint24) {
if (x >= 1 << 24) _revertOverflow();
return uint24(x);
}
function toUint32(uint256 x) internal pure returns (uint32) {
if (x >= 1 << 32) _revertOverflow();
return uint32(x);
}
function toUint40(uint256 x) internal pure returns (uint40) {
if (x >= 1 << 40) _revertOverflow();
return uint40(x);
}
function toUint48(uint256 x) internal pure returns (uint48) {
if (x >= 1 << 48) _revertOverflow();
return uint48(x);
}
function toUint56(uint256 x) internal pure returns (uint56) {
if (x >= 1 << 56) _revertOverflow();
return uint56(x);
}
function toUint64(uint256 x) internal pure returns (uint64) {
if (x >= 1 << 64) _revertOverflow();
return uint64(x);
}
function toUint72(uint256 x) internal pure returns (uint72) {
if (x >= 1 << 72) _revertOverflow();
return uint72(x);
}
function toUint80(uint256 x) internal pure returns (uint80) {
if (x >= 1 << 80) _revertOverflow();
return uint80(x);
}
function toUint88(uint256 x) internal pure returns (uint88) {
if (x >= 1 << 88) _revertOverflow();
return uint88(x);
}
function toUint96(uint256 x) internal pure returns (uint96) {
if (x >= 1 << 96) _revertOverflow();
return uint96(x);
}
function toUint104(uint256 x) internal pure returns (uint104) {
if (x >= 1 << 104) _revertOverflow();
return uint104(x);
}
function toUint112(uint256 x) internal pure returns (uint112) {
if (x >= 1 << 112) _revertOverflow();
return uint112(x);
}
function toUint120(uint256 x) internal pure returns (uint120) {
if (x >= 1 << 120) _revertOverflow();
return uint120(x);
}
function toUint128(uint256 x) internal pure returns (uint128) {
if (x >= 1 << 128) _revertOverflow();
return uint128(x);
}
function toUint136(uint256 x) internal pure returns (uint136) {
if (x >= 1 << 136) _revertOverflow();
return uint136(x);
}
function toUint144(uint256 x) internal pure returns (uint144) {
if (x >= 1 << 144) _revertOverflow();
return uint144(x);
}
function toUint152(uint256 x) internal pure returns (uint152) {
if (x >= 1 << 152) _revertOverflow();
return uint152(x);
}
function toUint160(uint256 x) internal pure returns (uint160) {
if (x >= 1 << 160) _revertOverflow();
return uint160(x);
}
function toUint168(uint256 x) internal pure returns (uint168) {
if (x >= 1 << 168) _revertOverflow();
return uint168(x);
}
function toUint176(uint256 x) internal pure returns (uint176) {
if (x >= 1 << 176) _revertOverflow();
return uint176(x);
}
function toUint184(uint256 x) internal pure returns (uint184) {
if (x >= 1 << 184) _revertOverflow();
return uint184(x);
}
function toUint192(uint256 x) internal pure returns (uint192) {
if (x >= 1 << 192) _revertOverflow();
return uint192(x);
}
function toUint200(uint256 x) internal pure returns (uint200) {
if (x >= 1 << 200) _revertOverflow();
return uint200(x);
}
function toUint208(uint256 x) internal pure returns (uint208) {
if (x >= 1 << 208) _revertOverflow();
return uint208(x);
}
function toUint216(uint256 x) internal pure returns (uint216) {
if (x >= 1 << 216) _revertOverflow();
return uint216(x);
}
function toUint224(uint256 x) internal pure returns (uint224) {
if (x >= 1 << 224) _revertOverflow();
return uint224(x);
}
function toUint232(uint256 x) internal pure returns (uint232) {
if (x >= 1 << 232) _revertOverflow();
return uint232(x);
}
function toUint240(uint256 x) internal pure returns (uint240) {
if (x >= 1 << 240) _revertOverflow();
return uint240(x);
}
function toUint248(uint256 x) internal pure returns (uint248) {
if (x >= 1 << 248) _revertOverflow();
return uint248(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNED INTEGER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toInt8(int256 x) internal pure returns (int8) {
int8 y = int8(x);
if (x != y) _revertOverflow();
return y;
}
function toInt16(int256 x) internal pure returns (int16) {
int16 y = int16(x);
if (x != y) _revertOverflow();
return y;
}
function toInt24(int256 x) internal pure returns (int24) {
int24 y = int24(x);
if (x != y) _revertOverflow();
return y;
}
function toInt32(int256 x) internal pure returns (int32) {
int32 y = int32(x);
if (x != y) _revertOverflow();
return y;
}
function toInt40(int256 x) internal pure returns (int40) {
int40 y = int40(x);
if (x != y) _revertOverflow();
return y;
}
function toInt48(int256 x) internal pure returns (int48) {
int48 y = int48(x);
if (x != y) _revertOverflow();
return y;
}
function toInt56(int256 x) internal pure returns (int56) {
int56 y = int56(x);
if (x != y) _revertOverflow();
return y;
}
function toInt64(int256 x) internal pure returns (int64) {
int64 y = int64(x);
if (x != y) _revertOverflow();
return y;
}
function toInt72(int256 x) internal pure returns (int72) {
int72 y = int72(x);
if (x != y) _revertOverflow();
return y;
}
function toInt80(int256 x) internal pure returns (int80) {
int80 y = int80(x);
if (x != y) _revertOverflow();
return y;
}
function toInt88(int256 x) internal pure returns (int88) {
int88 y = int88(x);
if (x != y) _revertOverflow();
return y;
}
function toInt96(int256 x) internal pure returns (int96) {
int96 y = int96(x);
if (x != y) _revertOverflow();
return y;
}
function toInt104(int256 x) internal pure returns (int104) {
int104 y = int104(x);
if (x != y) _revertOverflow();
return y;
}
function toInt112(int256 x) internal pure returns (int112) {
int112 y = int112(x);
if (x != y) _revertOverflow();
return y;
}
function toInt120(int256 x) internal pure returns (int120) {
int120 y = int120(x);
if (x != y) _revertOverflow();
return y;
}
function toInt128(int256 x) internal pure returns (int128) {
int128 y = int128(x);
if (x != y) _revertOverflow();
return y;
}
function toInt136(int256 x) internal pure returns (int136) {
int136 y = int136(x);
if (x != y) _revertOverflow();
return y;
}
function toInt144(int256 x) internal pure returns (int144) {
int144 y = int144(x);
if (x != y) _revertOverflow();
return y;
}
function toInt152(int256 x) internal pure returns (int152) {
int152 y = int152(x);
if (x != y) _revertOverflow();
return y;
}
function toInt160(int256 x) internal pure returns (int160) {
int160 y = int160(x);
if (x != y) _revertOverflow();
return y;
}
function toInt168(int256 x) internal pure returns (int168) {
int168 y = int168(x);
if (x != y) _revertOverflow();
return y;
}
function toInt176(int256 x) internal pure returns (int176) {
int176 y = int176(x);
if (x != y) _revertOverflow();
return y;
}
function toInt184(int256 x) internal pure returns (int184) {
int184 y = int184(x);
if (x != y) _revertOverflow();
return y;
}
function toInt192(int256 x) internal pure returns (int192) {
int192 y = int192(x);
if (x != y) _revertOverflow();
return y;
}
function toInt200(int256 x) internal pure returns (int200) {
int200 y = int200(x);
if (x != y) _revertOverflow();
return y;
}
function toInt208(int256 x) internal pure returns (int208) {
int208 y = int208(x);
if (x != y) _revertOverflow();
return y;
}
function toInt216(int256 x) internal pure returns (int216) {
int216 y = int216(x);
if (x != y) _revertOverflow();
return y;
}
function toInt224(int256 x) internal pure returns (int224) {
int224 y = int224(x);
if (x != y) _revertOverflow();
return y;
}
function toInt232(int256 x) internal pure returns (int232) {
int232 y = int232(x);
if (x != y) _revertOverflow();
return y;
}
function toInt240(int256 x) internal pure returns (int240) {
int240 y = int240(x);
if (x != y) _revertOverflow();
return y;
}
function toInt248(int256 x) internal pure returns (int248) {
int248 y = int248(x);
if (x != y) _revertOverflow();
return y;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function toInt256(uint256 x) internal pure returns (int256) {
if (x >= 1 << 255) _revertOverflow();
return int256(x);
}
function toUint256(int256 x) internal pure returns (uint256) {
if (x < 0) _revertOverflow();
return uint256(x);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertOverflow() private pure {
/// @solidity memory-safe-assembly
assembly {
// Store the function selector of `Overflow()`.
mstore(0x00, 0x35278d12)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { BalancerV2Data } from "../AugustusV6Types.sol";
/// @title IBalancerV2SwapExactAmountOut
/// @notice Interface for executing swapExactAmountOut directly on Balancer V2 pools
interface IBalancerV2SwapExactAmountOut is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountOut on Balancer V2 pools
/// @param balancerData Struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit Permit data for the swap
/// @param data The calldata to execute
/// @return spentAmount The actual amount of tokens used to swap
/// @return receivedAmount The amount of tokens received
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountOutOnBalancerV2(
BalancerV2Data calldata balancerData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata data
)
external
payable
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { UniswapV2Data } from "../AugustusV6Types.sol";
/// @title IUniswapV2SwapExactAmountOut
/// @notice Interface for direct swapExactAmountOut on Uniswap V2
interface IUniswapV2SwapExactAmountOut is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountOut on Uniswap V2 pools
/// @param swapData struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @return spentAmount The actual amount of tokens used to swap
/// @return receivedAmount The amount of tokens received
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountOutOnUniswapV2(
UniswapV2Data calldata swapData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { UniswapV3Data } from "../AugustusV6Types.sol";
/// @title IUniswapV3SwapExactAmountOut
/// @notice Interface for executing direct swapExactAmountOut on Uniswap V3
interface IUniswapV3SwapExactAmountOut is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @notice Executes a swapExactAmountOut on Uniswap V3 pools
/// @param swapData struct containing data for the swap
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @return spentAmount The actual amount of tokens used to swap
/// @return receivedAmount The amount of tokens received
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountOutOnUniswapV3(
UniswapV3Data calldata swapData,
uint256 partnerAndFee,
bytes calldata permit
)
external
payable
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
/// @title IAugustusFeeVault
/// @notice Interface for the AugustusFeeVault contract
interface IAugustusFeeVault {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Error emitted when withdraw amount is zero or exceeds the stored amount
error InvalidWithdrawAmount();
/// @notice Error emmitted when caller is not an approved augustus contract
error UnauthorizedCaller();
/// @notice Error emitted when an invalid parameter length is passed
error InvalidParameterLength();
/// @notice Error emitted when batch withdraw fails
error BatchCollectFailed();
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when an augustus contract approval status is set
/// @param augustus The augustus contract address
/// @param approved The approval status
event AugustusApprovalSet(address indexed augustus, bool approved);
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/// @notice Struct to register fees
/// @param addresses The addresses to register fees for
/// @param token The token to register fees for
/// @param fees The fees to register
struct FeeRegistration {
address[] addresses;
IERC20 token;
uint256[] fees;
}
/*//////////////////////////////////////////////////////////////
COLLECT
//////////////////////////////////////////////////////////////*/
/// @notice Allows partners to withdraw fees allocated to them and stored in the vault
/// @param token The token to withdraw fees in
/// @param amount The amount of fees to withdraw
/// @param recipient The address to send the fees to
/// @return success Whether the transfer was successful or not
function withdrawSomeERC20(IERC20 token, uint256 amount, address recipient) external returns (bool success);
/// @notice Allows partners to withdraw all fees allocated to them and stored in the vault for a given token
/// @param token The token to withdraw fees in
/// @param recipient The address to send the fees to
/// @return success Whether the transfer was successful or not
function withdrawAllERC20(IERC20 token, address recipient) external returns (bool success);
/// @notice Allows partners to withdraw all fees allocated to them and stored in the vault for multiple tokens
/// @param tokens The tokens to withdraw fees i
/// @param recipient The address to send the fees to
/// @return success Whether the transfer was successful or not
function batchWithdrawAllERC20(IERC20[] calldata tokens, address recipient) external returns (bool success);
/// @notice Allows partners to withdraw fees allocated to them and stored in the vault
/// @param tokens The tokens to withdraw fees in
/// @param amounts The amounts of fees to withdraw
/// @param recipient The address to send the fees to
/// @return success Whether the transfer was successful or not
function batchWithdrawSomeERC20(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
)
external
returns (bool success);
/*//////////////////////////////////////////////////////////////
BALANCE GETTERS
//////////////////////////////////////////////////////////////*/
/// @notice Get the balance of a given token for a given partner
/// @param token The token to get the balance of
/// @param partner The partner to get the balance for
/// @return feeBalance The balance of the given token for the given partner
function getBalance(IERC20 token, address partner) external view returns (uint256 feeBalance);
/// @notice Get the balances of a given partner for multiple tokens
/// @param tokens The tokens to get the balances of
/// @param partner The partner to get the balances for
/// @return feeBalances The balances of the given tokens for the given partner
function batchGetBalance(
IERC20[] calldata tokens,
address partner
)
external
view
returns (uint256[] memory feeBalances);
/// @notice Returns the unallocated fees for a given token
/// @param token The token to get the unallocated fees for
/// @return unallocatedFees The unallocated fees for the given token
function getUnallocatedFees(IERC20 token) external view returns (uint256 unallocatedFees);
/*//////////////////////////////////////////////////////////////
OWNER
//////////////////////////////////////////////////////////////*/
/// @notice Registers the given feeData to the vault
/// @param feeData The fee registration data
function registerFees(FeeRegistration memory feeData) external;
/// @notice Sets the augustus contract approval status
/// @param augustus The augustus contract address
/// @param approved The approval status
function setAugustusApproval(address augustus, bool approved) external;
/// @notice Sets the contract pause state
/// @param _isPaused The new pause state
function setContractPauseState(bool _isPaused) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/// @title IAugustusFees
/// @notice Interface for the AugustusFees contract, which handles the fees for the Augustus aggregator
interface IAugustusFees {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Error emmited when the balance is not enough to pay the fees
error InsufficientBalanceToPayFees();
/// @notice Error emmited when the quotedAmount is bigger than the fromAmount
error InvalidQuotedAmount();
/*//////////////////////////////////////////////////////////////
PUBLIC
//////////////////////////////////////////////////////////////*/
/// @notice Parses the `partnerAndFee` parameter to extract the partner address and fee data.
/// @dev `partnerAndFee` is a uint256 value where data is packed in a specific bit layout.
///
/// The bit layout for `partnerAndFee` is as follows:
/// - The most significant 160 bits (positions 255 to 96) represent the partner address.
/// - Bits 95 to 92 are reserved for flags indicating various fee processing conditions:
/// - 95th bit: `IS_TAKE_SURPLUS_MASK` - Partner takes surplus
/// - 94th bit: `IS_REFERRAL_MASK` - Referral takes surplus
/// - 93rd bit: `IS_SKIP_BLACKLIST_MASK` - Bypass token blacklist when processing fees
/// - 92nd bit: `IS_CAP_SURPLUS_MASK` - Cap surplus to 1% of quoted amount
/// - The least significant 16 bits (positions 15 to 0) encode the fee percentage.
///
/// @param partnerAndFee Packed uint256 containing both partner address and fee data.
/// @return partner The extracted partner address as a payable address.
/// @return feeData The extracted fee data containing the fee percentage and flags.
function parsePartnerAndFeeData(uint256 partnerAndFee)
external
pure
returns (address payable partner, uint256 feeData);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
// @title AugustusStorage
// @notice Inherited storage layout for AugustusV6,
// contracts should inherit this contract to access the storage layout
contract AugustusStorage {
/*//////////////////////////////////////////////////////////////
FEES
//////////////////////////////////////////////////////////////*/
// @dev Mapping of tokens to boolean indicating if token is blacklisted for fee collection
mapping(IERC20 token => bool isBlacklisted) public blacklistedTokens;
// @dev Fee wallet to directly transfer paraswap share to
address payable public feeWallet;
// @dev Fee wallet address to register the paraswap share to in the fee vault
address payable public feeWalletDelegate;
/*//////////////////////////////////////////////////////////////
CONTROL
//////////////////////////////////////////////////////////////*/
// @dev Contract paused state
bool public paused;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Contracts
import { AugustusFees } from "../fees/AugustusFees.sol";
// Utils
import { Permit2Utils } from "./Permit2Utils.sol";
import { PauseUtils } from "./PauseUtils.sol";
/// @title GenericUtils
/// @notice A contract containing common utilities for Generic swaps
abstract contract GenericUtils is AugustusFees, Permit2Utils, PauseUtils {
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
/// @dev Call executor with executorData and amountIn
function _callSwapExactAmountInExecutor(
address executor,
bytes calldata executorData,
uint256 amountIn
)
internal
{
// solhint-disable-next-line no-inline-assembly
assembly {
// get the length of the executorData
// + 4 bytes for the selector
// + 32 bytes for fromAmount
// + 32 bytes for sender
let totalLength := add(executorData.length, 68)
calldatacopy(add(0x7c, 4), executorData.offset, executorData.length) // store the executorData
mstore(add(0x7c, add(4, executorData.length)), amountIn) // store the amountIn
mstore(add(0x7c, add(36, executorData.length)), caller()) // store the sender
// call executor and forward call value
if iszero(call(gas(), executor, callvalue(), 0x7c, totalLength, 0, 0)) {
returndatacopy(0x7c, 0, returndatasize()) // copy the revert data to memory
revert(0x7c, returndatasize()) // revert with the revert data
}
}
}
/// @dev Call executor with executorData, maxAmountIn, amountOut
function _callSwapExactAmountOutExecutor(
address executor,
bytes calldata executorData,
uint256 maxAmountIn,
uint256 amountOut
)
internal
{
// solhint-disable-next-line no-inline-assembly
assembly {
// get the length of the executorData
// + 4 bytes for the selector
// + 32 bytes for fromAmount
// + 32 bytes for toAmount
// + 32 bytes for sender
let totalLength := add(executorData.length, 100)
calldatacopy(add(0x7c, 4), executorData.offset, executorData.length) // store the executorData
mstore(add(0x7c, add(4, executorData.length)), maxAmountIn) // store the maxAmountIn
mstore(add(0x7c, add(36, executorData.length)), amountOut) // store the amountOut
mstore(add(0x7c, add(68, executorData.length)), caller()) // store the sender
// call executor and forward call value
if iszero(call(gas(), executor, callvalue(), 0x7c, totalLength, 0, 0)) {
returndatacopy(0x7c, 0, returndatasize()) // copy the revert data to memory
revert(0x7c, returndatasize()) // revert with the revert data
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { GenericData } from "../AugustusV6Types.sol";
/// @title IGenericSwapExactAmountIn
/// @notice Interface for executing a generic swapExactAmountIn through an Augustus executor
interface IGenericSwapExactAmountIn is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT IN
//////////////////////////////////////////////////////////////*/
/// @notice Executes a generic swapExactAmountIn using the given executorData on the given executor
/// @param executor The address of the executor contract to use
/// @param swapData Generic data containing the swap information
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @param executorData The data to execute on the executor
/// @return receivedAmount The amount of destToken received after fees
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountIn(
address executor,
GenericData calldata swapData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata executorData
)
external
payable
returns (uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { GenericData } from "../AugustusV6Types.sol";
/// @title IGenericSwapExactAmountOut
/// @notice Interface for executing a generic swapExactAmountOut through an Augustus executor
interface IGenericSwapExactAmountOut is IErrors {
/*//////////////////////////////////////////////////////////////
SWAP EXACT AMOUNT OUT
//////////////////////////////////////////////////////////////*/
/// @notice Executes a generic swapExactAmountOut using the given executorData on the given executor
/// @param executor The address of the executor contract to use
/// @param swapData Generic data containing the swap information
/// @param partnerAndFee packed partner address and fee percentage, the first 12 bytes is the feeData and the last
/// 20 bytes is the partner address
/// @param permit The permit data
/// @param executorData The data to execute on the executor
/// @return spentAmount The actual amount of tokens used to swap
/// @return receivedAmount The amount of tokens received from the swap
/// @return paraswapShare The share of the fees for Paraswap
/// @return partnerShare The share of the fees for the partner
function swapExactAmountOut(
address executor,
GenericData calldata swapData,
uint256 partnerAndFee,
bytes calldata permit,
bytes calldata executorData
)
external
payable
returns (uint256 spentAmount, uint256 receivedAmount, uint256 paraswapShare, uint256 partnerShare);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
// Interfaces
import { IErrors } from "./IErrors.sol";
// Types
import { AugustusRFQData, OrderInfo } from "../AugustusV6Types.sol";
/// @title IAugustusRFQRouter
/// @notice Interface for direct swaps on AugustusRFQ
interface IAugustusRFQRouter is IErrors {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when the passed msg.value is not equal to the fromAmount
error IncorrectEthAmount();
/*//////////////////////////////////////////////////////////////
TRY BATCH FILL
//////////////////////////////////////////////////////////////*/
/// @notice Executes a tryBatchFillTakerAmount or tryBatchFillMakerAmount call on AugustusRFQ
/// the function that is executed is defined by the direction flag in the data param
/// @param data Struct containing common data for AugustusRFQ
/// @param orders An array containing AugustusRFQ orderInfo data
/// @param permit Permit data for the swap
/// @return spentAmount The amount of tokens spent
/// @return receivedAmount The amount of tokens received
function swapOnAugustusRFQTryBatchFill(
AugustusRFQData calldata data,
OrderInfo[] calldata orders,
bytes calldata permit
)
external
payable
returns (uint256 spentAmount, uint256 receivedAmount);
}
// SPDX-License-Identifier: ISC
pragma solidity 0.8.22;
pragma abicoder v2;
// Types
import { Order, OrderInfo } from "../AugustusV6Types.sol";
interface IAugustusRFQ {
/// @dev Allows taker to fill an order
/// @param order Order quote to fill
/// @param signature Signature of the maker corresponding to the order
function fillOrder(Order calldata order, bytes calldata signature) external;
/// @dev The same as fillOrder but allows sender to specify the target beneficiary address
/// @param order Order quote to fill
/// @param signature Signature of the maker corresponding to the order
/// @param target Address of the receiver
function fillOrderWithTarget(Order calldata order, bytes calldata signature, address target) external;
/// @dev Allows taker to fill an order partially
/// @param order Order quote to fill
/// @param signature Signature of the maker corresponding to the order
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
function partialFillOrder(
Order calldata order,
bytes calldata signature,
uint256 takerTokenFillAmount
)
external
returns (uint256 makerTokenFilledAmount);
/// @dev Same as `partialFillOrder` but it allows to specify the destination address
/// @param order Order quote to fill
/// @param signature Signature of the maker corresponding to the order
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param target Address that will receive swap funds
function partialFillOrderWithTarget(
Order calldata order,
bytes calldata signature,
uint256 takerTokenFillAmount,
address target
)
external
returns (uint256 makerTokenFilledAmount);
/// @dev Same as `partialFillOrderWithTarget` but it allows to pass permit
/// @param order Order quote to fill
/// @param signature Signature of the maker corresponding to the order
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param target Address that will receive swap funds
/// @param permitTakerAsset Permit calldata for taker
/// @param permitMakerAsset Permit calldata for maker
function partialFillOrderWithTargetPermit(
Order calldata order,
bytes calldata signature,
uint256 takerTokenFillAmount,
address target,
bytes calldata permitTakerAsset,
bytes calldata permitMakerAsset
)
external
returns (uint256 makerTokenFilledAmount);
/// @dev batch fills orders until the takerFillAmount is swapped
/// @dev skip the order if it fails
/// @param orderInfos OrderInfo to fill
/// @param takerFillAmount total taker amount to fill
/// @param target Address of receiver
function tryBatchFillOrderTakerAmount(
OrderInfo[] calldata orderInfos,
uint256 takerFillAmount,
address target
)
external;
/// @dev batch fills orders until the makerFillAmount is swapped
/// @dev skip the order if it fails
/// @param orderInfos OrderInfo to fill
/// @param makerFillAmount total maker amount to fill
/// @param target Address of receiver
function tryBatchFillOrderMakerAmount(
OrderInfo[] calldata orderInfos,
uint256 makerFillAmount,
address target
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol";
/// @title IWETH
/// @notice An interface for WETH IERC20
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/// @title IErrors
/// @notice Common interface for errors
interface IErrors {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when the returned amount is less than the minimum amount
error InsufficientReturnAmount();
/// @notice Emitted when the specified toAmount is less than the minimum amount (2)
error InvalidToAmount();
/// @notice Emmited when the srcToken and destToken are the same
error ArbitrageNotSupported();
}
File 2 of 4: TetherToken
pragma solidity ^0.4.17;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
// additional variables for use if transaction fees ever became necessary
uint public basisPointsRate = 0;
uint public maximumFee = 0;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(msg.sender, owner, fee);
}
Transfer(msg.sender, _to, sendAmount);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(_from, owner, fee);
}
Transfer(_from, _to, sendAmount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract UpgradedStandardToken is StandardToken{
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
contract TetherToken is Pausable, StandardToken, BlackList {
string public name;
string public symbol;
uint public decimals;
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
if (deprecated) {
return StandardToken(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
} else {
return _totalSupply;
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
Redeem(amount);
}
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints < 20);
require(newMaxFee < 50);
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(10**decimals);
Params(basisPointsRate, maximumFee);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
// Called if contract ever adds fees
event Params(uint feeBasisPoints, uint maxFee);
}File 3 of 4: CreditVault
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {EIP712, ECDSA} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "./libraries/ConstantsLib.sol";
import {ErrorsLib} from "./libraries/ErrorsLib.sol";
import {SafeERC20} from "./libraries/SafeERC20.sol";
import {ICreditVault} from "./interfaces/ICreditVault.sol";
import {ReentrancyGuardTransient} from "./libraries/ReentrancyGuardTransient.sol";
import {NativeLPToken} from "./NativeLPToken.sol";
/// @title CreditVault - Manages trader positions and collateral
/// @notice Handles asset custody, position settlement, and LP token integration
contract CreditVault is ICreditVault, EIP712, Ownable2Step, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
/*//////////////////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Address that can withdraw protocol fees
address public feeWithdrawer;
/// @notice signer for permissioned functions: liquidate, settle, removeCollateral, etc.
address public signer;
/// @notice epoch updater address
address public epochUpdater;
/// @notice A list of all markets
NativeLPToken[] public allLPTokens;
/// @notice Authorized Native Pool, enable market makers to lend funds from this vault for quoting
/// @dev The credit pool lends tokens from the credit vault and must update the trader's position via a callback.
mapping(address => bool) public creditPools;
/// @notice Mapping of accumulated reserveFees per token (token => fee amount)
mapping(address => uint256) public reserveFees;
/// @notice (trader => timestamp)
mapping(address => uint256) public lastEpochUpdateTimestamp;
/// @notice map from underlying address to LP token
mapping(address => NativeLPToken) public lpTokens;
// @notice Mapping to track used nonces for preventing replay attacks
mapping(uint256 => bool) public nonces;
/// @notice trader_address => underlying token => amount (positive for long, negative for short)
mapping(address => mapping(address => int256)) public positions;
/// @notice traders' collateral trader => token => amount
mapping(address => mapping(address => uint256)) public collateral;
/// @dev If a LP token is supported
mapping(address => bool) public supportedMarkets;
/// @notice whitelist for traders (Market Makers)
mapping(address => bool) public traders;
/// @notice Maps trader address to settler address which can settle positions on behalf of trader
mapping(address => address) public traderToSettler;
/// @notice maps trader to their recipient address
/// @dev Address receives tokens from settlements and collateral operations
mapping(address => address) public traderToRecipient;
/// @notice whitelist traders that can bypass the credit check
mapping(address => bool) public whitelistTraders;
/// @notice whitelist for liquidators
mapping(address => bool) public liquidators;
/// @notice maps liquidator to their recipient address for liquidations
mapping(address => address) public liquidatorToRecipient;
/// @notice Tracks rebalance caps for each trader/liquidator and token
mapping(address => mapping(address => RebalanceCap)) public rebalanceCaps;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
constructor() EIP712("Native Credit Vault", "1") {}
/// @notice Callback function called by NativeRFQPool after swap execution to update trader positions
/// @dev Only callable by whitelisted NativePools, it's called after the swap is executed
/// @param trader The address of the market maker
/// @param tokenIn The address of the token that is selling
/// @param amountIn The amount of the token that is selling
/// @param tokenOut The address of the token that is buying
/// @param amountOut The amount of the token that is buying
function swapCallback(
address trader,
address tokenIn,
int256 amountIn,
address tokenOut,
int256 amountOut
) external {
require(creditPools[msg.sender], ErrorsLib.OnlyCreditPool());
require(
address(lpTokens[tokenIn]) != address(0) && address(lpTokens[tokenOut]) != address(0),
ErrorsLib.InvalidUnderlying()
);
positions[trader][tokenIn] += amountIn;
positions[trader][tokenOut] -= amountOut;
}
/*//////////////////////////////////////////////////////////////////////////
PERMISSIONED FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Updates funding fees for traders at the end of each epoch
/// @dev Only callable by the epoch updater
/// @param accruedFees Array of funding fee updates for different traders
function epochUpdate(AccruedFundingFee[] calldata accruedFees) external {
require(msg.sender == epochUpdater, ErrorsLib.OnlyEpochUpdater());
for (uint256 i; i < accruedFees.length; ++i) {
address trader = accruedFees[i].trader;
if (block.timestamp - lastEpochUpdateTimestamp[trader] < EPOCH_UPDATE_INTERVAL) {
revert ErrorsLib.EpochUpdateInCoolDown();
}
for (uint256 j; j < accruedFees[i].feeUpdates.length; ++j) {
address token = accruedFees[i].feeUpdates[j].token;
uint256 fundingFee = accruedFees[i].feeUpdates[j].fundingFee;
uint256 reserveFee = accruedFees[i].feeUpdates[j].reserveFee;
// Check if the underlying token is supported
require(address(lpTokens[token]) != address(0), ErrorsLib.InvalidUnderlying());
if (fundingFee > 0) {
uint256 beforeExchangeRate = lpTokens[token].exchangeRate();
// Distribute funding fee to all LPToken holders
lpTokens[token].distributeYield(fundingFee);
// Verify the exchange rate increase is not more than 1%
if (((lpTokens[token].exchangeRate() - beforeExchangeRate) * 10_000) > beforeExchangeRate * 100) {
revert ErrorsLib.ExchangeRateIncreaseTooMuch();
}
}
if (reserveFee > 0) {
reserveFees[token] += reserveFee;
}
// Subtract reserve fee and funding fee from the trader's position
positions[trader][token] -= (reserveFee + fundingFee).toInt256();
}
lastEpochUpdateTimestamp[trader] = block.timestamp;
}
emit EpochUpdated(accruedFees);
}
/// @notice Called by traders to settle the positions
/// @dev This transaction requires off-chain calculation to verify if the trader's credit meets the criteria.
/// @param request The struct of the settlement request containing info of long and short positions to settle
/// @param signature The signature of the settlement request
function settle(
SettlementRequest calldata request,
bytes calldata signature
) external onlyTraderOrSettler(request.trader) nonReentrant {
_verifySettleSignature(request, signature);
_updatePositions(request.positionUpdates, request.trader);
address recipient = traderToRecipient[request.trader];
// execute token transfers
for (uint256 i; i < request.positionUpdates.length; ++i) {
address token = request.positionUpdates[i].token;
int256 amount = request.positionUpdates[i].amount;
if (amount > 0) {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount.toUint256());
} else {
/// Enforce rebalance cap before funds leave vault to ensure limit compliance
_updateRebalanceCap(request.trader, token, (-amount).toUint256());
IERC20(token).safeTransfer(recipient, (-amount).toUint256());
}
}
emit Settled(request.trader, request.positionUpdates);
}
/// @notice Called by traders to remove collateral
/// @dev This transaction requires off-chain calculation to verify if the trader's credit meets the criteria.
/// @param request The struct of the remove collateral request containing info of collateral to remove
/// @param signature The signature of the remove collateral request
function removeCollateral(
RemoveCollateralRequest calldata request,
bytes calldata signature
) external onlyTraderOrSettler(request.trader) nonReentrant {
_verifyRemoveCollateralSignature(request, signature);
for (uint256 i; i < request.tokens.length; ++i) {
collateral[request.trader][request.tokens[i].token] -= request.tokens[i].amount;
}
address recipient = traderToRecipient[request.trader];
for (uint256 i; i < request.tokens.length; ++i) {
address token = request.tokens[i].token;
uint256 amount = request.tokens[i].amount;
/// Enforce rebalance cap before funds leave vault
_updateRebalanceCap(request.trader, token, amount);
IERC20(token).safeTransfer(recipient, amount);
}
emit CollateralRemoved(request.trader, request.tokens);
}
/// @notice Repays trader's short positions
/// @param positionUpdates Array of {token, amount} structs representing positions to repay
/// @param trader Address of the trader whose positions are being repaid
function repay(
TokenAmountInt[] calldata positionUpdates,
address trader
) external onlyTraderOrSettler(trader) nonReentrant {
_updatePositions(positionUpdates, trader);
// the safeCast to Uint256 will revert if the repayments amount is negative
for (uint256 i; i < positionUpdates.length; ++i) {
IERC20(positionUpdates[i].token).safeTransferFrom(
msg.sender, address(this), positionUpdates[i].amount.toUint256()
);
}
emit Repaid(trader, positionUpdates);
}
/// @notice Called by liquidators to liquidate the underwater positions
/// @dev This transaction requires off-chain calculation to verify if the trader's credit meets the criteria.
/// @param request The struct of the liquidation request containing info of long and short positions to liquidate
/// @param signature The signature of the liquidation request
function liquidate(
LiquidationRequest calldata request,
bytes calldata signature
) external onlyLiquidator nonReentrant {
_verifyLiquidationSignature(request, signature);
_updatePositions(request.positionUpdates, request.trader);
address recipient = liquidatorToRecipient[msg.sender];
for (uint256 i; i < request.claimCollaterals.length; ++i) {
collateral[request.trader][request.claimCollaterals[i].token] -= request.claimCollaterals[i].amount;
}
for (uint256 i; i < request.positionUpdates.length; ++i) {
address token = request.positionUpdates[i].token;
int256 amount = request.positionUpdates[i].amount;
if (amount > 0) {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount.toUint256());
} else {
/// Enforce rebalance cap before underlying token leave vault
_updateRebalanceCap(msg.sender, token, (-amount).toUint256());
IERC20(token).safeTransfer(recipient, (-amount).toUint256());
}
}
for (uint256 i; i < request.claimCollaterals.length; ++i) {
address token = request.claimCollaterals[i].token;
/// Enforce rebalance cap before collateral token leave vault
_updateRebalanceCap(msg.sender, token, request.claimCollaterals[i].amount);
IERC20(token).safeTransfer(recipient, request.claimCollaterals[i].amount);
}
emit Liquidated(request.trader, msg.sender, request.positionUpdates, request.claimCollaterals);
}
/// @notice Transfers underlying assets from vault to recipient
/// @dev Only callable by supported LP tokens
/// @param to Recipient of the underlying assets
/// @param amount Amount of underlying assets to transfer
function pay(address to, uint256 amount) external {
require(supportedMarkets[msg.sender], ErrorsLib.OnlyLpToken());
require(amount <= NativeLPToken(msg.sender).totalUnderlying(), ErrorsLib.InsufficientUnderlying());
// Each LP token can only transfer its own underlying token
IERC20(NativeLPToken(msg.sender).underlying()).safeTransfer(to, amount);
}
/*//////////////////////////////////////////////////////////////////////////
PERMISSIONLESS FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Adds collateral for a trader's position
/// @dev PERMISSIONLESS: Anyone can add collateral for any trader
/// @dev Off-chain system will update trader's credit limit off-chain via event emission
/// @param tokens Array of {token, amount} structs to be added as collateral
/// @param trader Address of the trader receiving the collateral
function addCollateral(TokenAmountUint[] calldata tokens, address trader) external nonReentrant {
require(traders[trader], ErrorsLib.OnlyTrader());
for (uint256 i; i < tokens.length; ++i) {
address token = tokens[i].token;
require(supportedMarkets[token], ErrorsLib.OnlyLpToken());
uint256 amount = tokens[i].amount;
collateral[trader][token] += amount;
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
emit CollateralAdded(trader, tokens);
}
/*//////////////////////////////////////////////////////////////////////////
ADMIN FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Lists a new market (LP token)
/// @dev Only callable by owner
/// @param lpToken Address of the LP token to be listed
function supportMarket(NativeLPToken lpToken) external onlyOwner {
// Check if market is already listed
require(!supportedMarkets[address(lpToken)], ErrorsLib.TokenAlreadyListed());
address underlying = address(lpToken.underlying());
// Verify market configuration
require(
address(lpTokens[underlying]) == address(0) && lpToken.creditVault() == address(this),
ErrorsLib.InvalidMarket()
);
// Sanity check to make sure its really LPToken
require(address(underlying) != address(0), ErrorsLib.InvalidLPToken());
// Update storage
lpTokens[underlying] = lpToken;
supportedMarkets[address(lpToken)] = true;
allLPTokens.push(lpToken);
emit MarketListed(address(lpToken));
}
/// @notice Allows fee withdrawer to claim accumulated funding fees
/// @dev Only callable by feeWithdrawer
/// @param underlying The token address of the fees to withdraw
/// @param recipient The address that will receive the fees
/// @param amount The amount of fees to withdraw
function withdrawReserve(address underlying, address recipient, uint256 amount) external {
require(recipient != address(0), ErrorsLib.ZeroAddress());
require(msg.sender == feeWithdrawer, ErrorsLib.OnlyFeeWithdrawer());
require(amount <= reserveFees[underlying], ErrorsLib.InsufficientFundingFees());
reserveFees[underlying] -= amount;
// Withdraw underlying from vault
IERC20(underlying).safeTransfer(recipient, amount);
emit ReserveWithdrawn(underlying, recipient, amount);
}
/// @notice Updates credit pool status
/// @param pool The address of credit pool
/// @param isActive to whitelist, false to remove from whitelist
function setCreditPool(address pool, bool isActive) external onlyOwner {
require(pool != address(0), ErrorsLib.ZeroAddress());
creditPools[pool] = isActive;
emit CreditPoolUpdated(pool, isActive);
}
/// @notice Approves native pool to spend vault's underlying tokens
/// @dev Only callable by owner
/// @dev Pool must be whitelisted as native pool
/// @param tokens Array of {token, amount} structs to approve
/// @param pool Address of native pool to receive approval
function setAllowance(TokenAmountUint[] calldata tokens, address pool) external onlyOwner {
for (uint256 i; i < tokens.length; ++i) {
require(address(lpTokens[tokens[i].token]) != address(0), ErrorsLib.InvalidUnderlying());
IERC20(tokens[i].token).safeApprove(pool, tokens[i].amount);
}
}
/// @notice Set or update the daily rebalance limit for a specific trader or liquidator and token
/// @dev A limit of 0 means unlimited rebalancing is allowed
/// @param operator The address of the trader or liquidator whose limit is being set
/// @param token The token address for which the limit applies
/// @param limit The maximum amount of tokens that can be rebalanced per day (0 for unlimited)
function setRebalanceCap(address operator, address token, uint256 limit) external onlyOwner {
require(token != address(0), ErrorsLib.ZeroAddress());
require(traders[operator] || liquidators[operator], ErrorsLib.NotTraderOrLiquidator());
// used will be reset to 0
rebalanceCaps[operator][token] = RebalanceCap({limit: limit, used: 0, lastDay: block.timestamp / 86_400});
emit RebalanceCapUpdated(operator, token, limit);
}
/// @notice Manages trader permissions and settlement addresses
/// @dev Only callable by owner
/// @param trader Address to configure trading permissions for
/// @param settler Address authorized to settle positions on trader's behalf
/// @param recipient Address authorized to receive tokens from settlements and collateral operations
/// @param isTrader True to enable trading, false to revoke permissions
/// @param isWhitelistTrader True to enable whitelist which can bypass credit check
function setTrader(
address trader,
address settler,
address recipient,
bool isTrader,
bool isWhitelistTrader
) external onlyOwner {
require(trader != address(0) && settler != address(0) && recipient != address(0), ErrorsLib.ZeroAddress());
require(recipient != trader && recipient != settler, ErrorsLib.TraderRecipientConflict());
traders[trader] = isTrader;
traderToSettler[trader] = settler;
traderToRecipient[trader] = recipient;
whitelistTraders[trader] = isWhitelistTrader;
emit TraderSet(trader, isTrader, isWhitelistTrader, settler, recipient);
}
/// @notice Set or remove liquidator permissions
/// @dev Only callable by owner
/// @param liquidator The address to grant/revoke liquidator permissions
/// @param recipient Address authorized to receive tokens from liquidations
/// @param status True to whitelist, false to remove from whitelist
function setLiquidator(address liquidator, address recipient, bool status) external onlyOwner {
require(liquidator != address(0) && recipient != address(0), ErrorsLib.ZeroAddress());
require(liquidator != recipient, ErrorsLib.LiquidatorRecipientConflict());
liquidators[liquidator] = status;
liquidatorToRecipient[liquidator] = recipient;
emit LiquidatorSet(liquidator, status);
}
/// @notice Updates the authorized signer for permissioned operations
/// @dev Only callable by owner
/// @dev Signer verifies signatures for settlements, liquidations, and collateral removals
/// @param _signer New signer address (cannot be zero address)
function setSigner(address _signer) external onlyOwner {
require(_signer != address(0), ErrorsLib.ZeroAddress());
signer = _signer;
emit SignerSet(_signer);
}
/// @notice Updates the authorized epoch updater address
/// @dev Only callable by owner
/// @dev Epoch updater is responsible for funding fee updates and distributions
/// @param _epochUpdater New epoch updater address (cannot be zero address)
function setEpochUpdater(address _epochUpdater) external onlyOwner {
require(_epochUpdater != address(0), ErrorsLib.ZeroAddress());
epochUpdater = _epochUpdater;
emit EpochUpdaterSet(_epochUpdater);
}
/// @notice Updates the authorized fee withdrawer address
/// @dev Only callable by owner
/// @dev Fee withdrawer can claim accumulated funding fees from the vault
/// @param _feeWithdrawer New fee withdrawer address (cannot be zero address)
function setFeeWithdrawer(address payable _feeWithdrawer) external onlyOwner {
require(_feeWithdrawer != address(0), ErrorsLib.ZeroAddress());
feeWithdrawer = _feeWithdrawer;
emit FeeWithdrawerSet(_feeWithdrawer);
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
function _updateNonce(uint256 nonce) internal {
require(!nonces[nonce], ErrorsLib.NonceUsed());
nonces[nonce] = true;
}
function _updatePositions(ICreditVault.TokenAmountInt[] memory positionUpdates, address trader) internal {
uint256 updatesLength = positionUpdates.length;
for (uint256 i; i < updatesLength; ++i) {
address token = positionUpdates[i].token;
int256 amount = positionUpdates[i].amount;
int256 newPosition = positions[trader][token] + amount;
// Make sure the token is supported underlying token
require(address(lpTokens[token]) != address(0), ErrorsLib.InvalidLPToken());
// Position must decrease without flipping its sign (e.g. long 100 -> long 50, not long 100 -> short 20)
if (positions[trader][token] * amount >= 0 || positions[trader][token] * newPosition < 0) {
revert ErrorsLib.InvalidPositionUpdateAmount();
}
positions[trader][token] = newPosition;
}
}
/// @notice Check and update daily rebalance tracking for a trader's token position
/// @param trader The address of the trader attempting to rebalance
/// @param token The token address being rebalanced, can be underlying token or collateral token
/// @param amount The amount of tokens being rebalanced
function _updateRebalanceCap(address trader, address token, uint256 amount) internal {
RebalanceCap storage cap = rebalanceCaps[trader][token];
uint256 currentDay = block.timestamp / 86_400;
uint256 newUsed;
// Reset daily used amount if it's a new day, otherwise add to existing
if (currentDay > cap.lastDay) {
newUsed = amount;
} else {
newUsed = cap.used + amount;
}
// Check if rebalance would exceed daily limit, skip check if limit is 0 (unlimited)
require(cap.limit == 0 || newUsed <= cap.limit, ErrorsLib.RebalanceLimitExceeded());
// Update storage in a single write
rebalanceCaps[trader][token] = RebalanceCap({limit: cap.limit, used: newUsed, lastDay: currentDay});
}
function _verifySettleSignature(
ICreditVault.SettlementRequest calldata request,
bytes calldata signature
) internal {
require(request.deadline >= block.timestamp, ErrorsLib.RequestExpired());
_updateNonce(request.nonce);
bytes32 msgHash = keccak256(
abi.encode(
SETTLEMENT_REQUEST_SIGNATURE_HASH,
request.nonce,
request.deadline,
request.trader,
keccak256(abi.encode(request.positionUpdates)),
traderToRecipient[request.trader]
)
);
bytes32 digest = _hashTypedDataV4(msgHash);
address recoveredSigner = ECDSA.recover(digest, signature);
require(recoveredSigner == signer, ErrorsLib.InvalidSignature());
}
function _verifyRemoveCollateralSignature(
ICreditVault.RemoveCollateralRequest calldata request,
bytes calldata signature
) internal {
require(request.deadline >= block.timestamp, ErrorsLib.RequestExpired());
_updateNonce(request.nonce);
bytes32 msgHash = keccak256(
abi.encode(
REMOVE_COLLATERAL_REQUEST_SIGNATURE_HASH,
request.nonce,
request.deadline,
request.trader,
keccak256(abi.encode(request.tokens)),
traderToRecipient[request.trader]
)
);
bytes32 digest = _hashTypedDataV4(msgHash);
address recoveredSigner = ECDSA.recover(digest, signature);
require(recoveredSigner == signer, ErrorsLib.InvalidSignature());
}
function _verifyLiquidationSignature(
ICreditVault.LiquidationRequest calldata request,
bytes calldata signature
) internal {
require(request.deadline >= block.timestamp, ErrorsLib.RequestExpired());
_updateNonce(request.nonce);
bytes32 msgHash = keccak256(
abi.encode(
LIQUIDATION_REQUEST_SIGNATURE_HASH,
request.nonce,
request.deadline,
request.trader,
keccak256(abi.encode(request.positionUpdates)),
keccak256(abi.encode(request.claimCollaterals)),
liquidatorToRecipient[msg.sender]
)
);
bytes32 digest = _hashTypedDataV4(msgHash);
address recoveredSigner = ECDSA.recover(digest, signature);
require(recoveredSigner == signer, ErrorsLib.InvalidSignature());
}
/*//////////////////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Separate the trader and settler accounts, they have different operation frequency and security setup requirements
modifier onlyTraderOrSettler(address trader) {
require(
(traders[trader] && trader == msg.sender) // Make sure a trader can only dispose of their own position
|| (traders[trader] && msg.sender == traderToSettler[trader]), // Trader's settler can also settle their own position
ErrorsLib.OnlyTrader()
);
_;
}
modifier onlyLiquidator() {
require(liquidators[msg.sender], ErrorsLib.OnlyLiquidator());
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @dev Contract module which provides 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} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.8;
import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/
function eip712Domain()
public
view
virtual
override
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_name.toStringWithFallback(_nameFallback),
_version.toStringWithFallback(_versionFallback),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @dev Every interval, the system performs an epoch update to calculate and settle funding fees between traders
uint256 constant EPOCH_UPDATE_INTERVAL = 8 hours;
/// @dev Maximum early withdrawal fee in basis points (10%)
uint256 constant MAX_EARLY_WITHDRAW_FEE_BIPS = 1000;
/// @dev Maximum widget fee in basis points (20%)
uint256 constant MAX_WIDGET_FEE_BIPS = 2000;
/// @dev The EIP-712 typeHash for Settle Market Maker Position Authorization.
bytes32 constant SETTLEMENT_REQUEST_SIGNATURE_HASH = keccak256(
"SettlementRequest(uint256 nonce,uint256 deadline,address trader,bytes32 positionUpdates,address recipient)"
);
/// @dev The EIP-712 typeHash for Remove Collateral Authorization.
bytes32 constant REMOVE_COLLATERAL_REQUEST_SIGNATURE_HASH =
keccak256("RemoveCollateralRequest(uint256 nonce,uint256 deadline,address trader,bytes32 tokens,address recipient)");
/// @dev The EIP-712 typeHash for Liquidation Authorization.
bytes32 constant LIQUIDATION_REQUEST_SIGNATURE_HASH = keccak256(
"LiquidationRequest(uint256 nonce,uint256 deadline,address trader,bytes32 positionUpdates,bytes32 claimCollaterals,address recipient)"
);
/// @dev The EIP-712 typeHash for Market Maker RFQ Quote Authorization.
bytes32 constant ORDER_SIGNATURE_HASH = keccak256(
"Order(uint256 id,address signer,address buyer,address seller,address buyerToken,address sellerToken,uint256 buyerTokenAmount,uint256 sellerTokenAmount,uint256 deadlineTimestamp,address caller,bytes16 quoteId)"
);
/// @dev The EIP-712 typeHash for RFQ Quote Widget Authorization.
bytes32 constant RFQ_QUOTE_WIDGET_SIGNATURE_HASH =
keccak256("RFQTQuote(bytes32 quote,address widgetFeeRecipient,uint256 widgetFeeRate)");
/// @dev The EIP-712 typeHash for Fill Order Authorization.
bytes32 constant FILL_ORDER_SIGNATURE_HASH = keccak256(
"fillOrder(uint256 nonce,address recipient,address tokenIn,address tokenOut,uint256 amountIn,uint256 amountOut,uint256 deadline,address widgetFeeRecipient,uint256 widgetFeeRate)"
);
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @title Custom error definitions for the protocol
/// @notice This library contains all the error definitions used throughout the contract
/// @dev The errors are arranged in alphabetical order
library ErrorsLib {
/// @notice Thrown when array lengths don't match in a function requiring equal-length arrays
error ArraysLengthMismatch();
/// @notice Thrown when deposit amount is below minimum required
error BelowMinimumDeposit();
/// @notice Thrown when caller is not the authorized epoch updater
error CallerNotEpochUpdater();
/// @notice Thrown when caller is not an authorized liquidator
error CallerNotLiquidator();
/// @notice Thrown when caller is not a trader or authorized settler
error CallerNotTraderSettler();
/// @notice Thrown when caller is not the WETH9 contract
error CallerNotWETH9();
/// @notice Thrown when epoch update is attempted before minimum interval
error EpochUpdateInCoolDown();
/// @notice Thrown when LP token exchange rate increases more than allowed
error ExchangeRateIncreaseTooMuch();
/// @notice Thrown when an external contract call fails
error ExternalCallFailed(address target, bytes4 selector);
/// @notice Thrown when feature is paused
error FeaturePaused();
/// @notice Thrown when there are insufficient funding fees to withdraw
error InsufficientFundingFees();
/// @notice Thrown when LP token shares are insufficient
error InsufficientShares();
/// @notice Thrown when LP token underlying is insufficient
error InsufficientUnderlying();
/// @notice Thrown when there is insufficient WETH9 to unwrap
error InsufficientWETH9();
/// @notice Thrown when an amount parameter is invalid
error InvalidAmount();
/// @notice Thrown when fee rate in basis points exceeds maximum (10000)
error InvalidFeeBips();
/// @notice Thrown when LP token address is invalid
error InvalidLPToken();
/// @notice Thrown when underlying are not supported in the credit vault
error InvalidUnderlying();
/// @notice Thrown when market (LP token) is invalid
error InvalidMarket();
/// @notice Thrown when position update amount is invalid
error InvalidPositionUpdateAmount();
/// @notice Thrown when the pool address is invalid Native pool
error InvalidNativePool();
/// @notice Thrown when signature verification fails
error InvalidSignature();
/// @notice Thrown when signer is not authorized
error InvalidSigner();
/// @notice Thrown when WETH9 unwrap amount is zero or exceeds balance
error InvalidWETH9Amount();
/// @notice Thrown when widget fee rate is invalid
error InvalidWidgetFeeRate();
/// @notice Thrown when liquidator and recipient are the same
error LiquidatorRecipientConflict();
/// @notice Thrown when nonce is used
error NonceUsed();
/// @notice Thrown when output amount is less than minimum required
error NotEnoughAmountOut(uint256 amountOut, uint256 amountOutMinimum);
/// @notice Thrown when insufficient token output received
error NotEnoughTokenReceived();
/// @notice Thrown the address is not a trader or liquidator
error NotTraderOrLiquidator();
/// @notice Error when caller is not a trusted operator
error NotTrustedOperator();
/// @notice Thrown when there is no yield to distribute
error NoYieldToDistribute();
/// @notice Thrown when caller is not the credit pool
error OnlyCreditPool();
/// @notice Thrown when caller is not the credit vault
error OnlyCreditVault();
/// @notice Thrown when caller is not the epoch updater
error OnlyEpochUpdater();
/// @notice Thrown when caller is not the fee withdrawer
error OnlyFeeWithdrawer();
/// @notice Thrown when caller is not an authorized liquidator
error OnlyLiquidator();
/// @notice Thrown when caller is not an LP token
error OnlyLpToken();
/// @notice Thrown when caller is not the native router
error OnlyNativeRouter();
/// @notice Thrown when caller is not the owner
error OnlyOwner();
/// @notice Thrown when caller is not an authorized trader
error OnlyTrader();
/// @notice Thrown when caller is not the WETH9 contract
error OnlyWETH9();
/// @notice Thrown when order has expired
error OrderExpired();
/// @notice Thrown when arithmetic operation would overflow
error Overflow();
/// @notice Thrown when permit2 token mismatch quote
error Permit2TokenMismatch();
/// @notice Thrown when LP pool has no deposits yet
error PoolNotInitialized();
/// @notice Thrown when quote has expired
error QuoteExpired();
/// @notice Thrown when rebalance limit is exceeded
error RebalanceLimitExceeded();
/// @notice Thrown when request has expired
error RequestExpired();
/// @notice Thrown when token is already listed
error TokenAlreadyListed();
/// @notice Thrown when trader, settler and recipient are the same
error TraderRecipientConflict();
/// @notice Thrown when transfer is in cooldown period
error TransferInCooldown();
/// @notice Thrown when transfer to self
error TransferSelf();
/// @notice Thrown when transfer to current contract
error TransferToContract();
/// @notice Thrown when unexpected msg.value is sent
error UnexpectedMsgValue();
/// @notice Thrown when zero address is provided
error ZeroAddress();
/// @notice Thrown when amount is zero
error ZeroAmount();
/// @notice Thrown when input is zero or empty
error ZeroInput();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
// Copy from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.9.6/contracts/token/ERC20/utils/SafeERC20.sol
// NOTE: We disable 'SafeApprove' function beblow feature
// same with uniswap v3 transferHelper: https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/TransferHelper.sol
// require(
// (value == 0) || (token.allowance(address(this), spender) == 0),
// "SafeERC20: approve from non-zero to non-zero allowance"
// );
import "openzeppelin/token/ERC20/IERC20.sol";
import "openzeppelin/utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @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.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// NOTE: we disable this
// 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));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
interface ICreditVault {
function swapCallback(
address signer,
address sellerToken,
int256 amount0Delta,
address buyerToken,
int256 amount1Delta
) external;
/// @notice Struct for tracking daily rebalance limits per trader/liquidator and token
/// @param limit Daily rebalance limit
/// @param used Amount rebalanced today
/// @param lastDay Last rebalance day timestamp
struct RebalanceCap {
uint256 limit;
uint256 used;
uint256 lastDay;
}
/// @notice Epoch Funding fee updates for a specific trader
/// @param trader The address of the trader
/// @param feeUpdates Array of funding fee updates for different tokens
struct AccruedFundingFee {
address trader;
FundingFeeAmount[] feeUpdates;
}
/// @notice Details of funding and reserve fees for a specific token
/// @param token The unerlying token address
/// @param fundingFee Amount of fee distributed to LP holders
/// @param reserveFee Amount of fee reserved for the protocol
struct FundingFeeAmount {
address token;
uint256 fundingFee;
uint256 reserveFee;
}
/// @notice Represents a token amount with unsigned integer value
/// @param token The address of underlying token
/// @param amount The unsigned amount of tokens
struct TokenAmountUint {
address token;
uint256 amount;
}
/// @notice Represents a token amount with signed integer value (for positions)
/// @param token The address of underlying token
/// @param amount The signed amount (positive for long, negative for short)
struct TokenAmountInt {
address token;
int256 amount;
}
/// @notice Request parameters for position settlement
/// @param nonce Unique identifier to prevent replay attacks
/// @param deadline Timestamp after which the request expires
/// @param trader Address of the trader whose positions are being settled
/// @param positionUpdates Array of position changes to be settled
struct SettlementRequest {
uint256 nonce;
uint256 deadline;
address trader;
TokenAmountInt[] positionUpdates;
}
/// @notice Request parameters for collateral removal
/// @param nonce Unique identifier to prevent replay attacks
/// @param deadline Timestamp after which the request expires
/// @param trader Address of the trader removing collateral
/// @param tokens Array of collateral tokens to be removed
struct RemoveCollateralRequest {
uint256 nonce;
uint256 deadline;
address trader;
TokenAmountUint[] tokens;
}
/// @notice Request parameters for position liquidation
/// @param nonce Unique identifier to prevent replay attacks
/// @param deadline Timestamp after which the request expires
/// @param trader Address of the trader being liquidated
/// @param positionUpdates Array of position changes from liquidation
/// @param claimCollaterals Array of collateral tokens to be claimed
struct LiquidationRequest {
uint256 nonce;
uint256 deadline;
address trader;
TokenAmountInt[] positionUpdates;
TokenAmountUint[] claimCollaterals;
}
/// @notice Emitted when a new market (LP token) is listed
/// @param lpToken The address of the newly listed LP token
event MarketListed(address lpToken);
/// @notice Emitted when epoch funding fees are updated for traders
/// @param accruedFundingFees Array of funding fee updates for different traders
event EpochUpdated(AccruedFundingFee[] accruedFundingFees);
/// @notice Emitted when a trader's positions are repaid
/// @param trader The address of the trader whose positions are being repaid
/// @param repayments Array of token amounts being repaid
event Repaid(address trader, TokenAmountInt[] repayments);
/// @notice Emitted when a trader's positions are settled
/// @param trader The address of the trader whose positions are being settled
/// @param positionUpdates Array of position changes
event Settled(address trader, TokenAmountInt[] positionUpdates);
/// @notice Emitted when collateral is added for a trader
/// @param trader The address of the trader receiving collateral
/// @param collateralUpdates Array of collateral token amounts added
event CollateralAdded(address trader, TokenAmountUint[] collateralUpdates);
/// @notice Emitted when collateral is removed for a trader
/// @param trader The address of the trader removing collateral
/// @param collateralUpdates Array of collateral token amounts removed
event CollateralRemoved(address trader, TokenAmountUint[] collateralUpdates);
/// @notice Emitted when a trader's positions are liquidated
/// @param trader The address of the trader being liquidated
/// @param liquidator The address performing the liquidation
/// @param positionUpdates Array of position changes from liquidation
/// @param claimCollaterals Array of collateral tokens claimed by liquidator
event Liquidated(
address trader, address liquidator, TokenAmountInt[] positionUpdates, TokenAmountUint[] claimCollaterals
);
/// @notice Emitted when a credit pool's status is updated
/// @param pool The address of the credit pool
/// @param isActive The new status of the pool
event CreditPoolUpdated(address indexed pool, bool isActive);
/// @notice Emitted when a trader or liquidator's rebalance limit is updated for a token
/// @param operator The trader or liquidator address
/// @param token The token address
/// @param limit The new daily limit (0 means unlimited)
event RebalanceCapUpdated(address indexed operator, address indexed token, uint256 limit);
/// @notice Emitted when a trader's info is updated
/// @param trader The address of the trader whose info is being updated
/// @param isTrader Whether the address is enabled for trading
/// @param isWhitelistTrader Whether the trader can bypass credit checks
/// @param settler The address authorized to settle positions for this trader
/// @param recipient The address authorized to receive tokens from settlements
event TraderSet(address indexed trader, bool isTrader, bool isWhitelistTrader, address settler, address recipient);
/// @notice Emitted when liquidator is set
event LiquidatorSet(address liquidator, bool status);
/// @notice Emitted when signer is set
event SignerSet(address signer);
/// @notice Emitted when epoch updater is set
event EpochUpdaterSet(address epochUpdater);
/// @notice Emitted when fee withdrawer is set
event FeeWithdrawerSet(address feeWithdrawer);
/// @notice Emitted when reserve fees are withdrawn
event ReserveWithdrawn(address underlying, address recipient, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {TStorage} from "./TStorage.sol";
// Refer from OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v5.1/contracts/utils/ReentrancyGuardTransient.sol
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*/
abstract contract ReentrancyGuardTransient {
using TStorage for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.tload();
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata as IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./libraries/ConstantsLib.sol";
import {CreditVault} from "./CreditVault.sol";
import {ErrorsLib} from "./libraries/ErrorsLib.sol";
import {ReentrancyGuardTransient} from "./libraries/ReentrancyGuardTransient.sol";
/// @title NativeLPToken - Yield-bearing LP token contract
/// @notice A token contract that represents liquidity provider positions and distributes yield
/// @dev This contract manages LP shares and underlying assets, accruing yield based on protocol revenue
contract NativeLPToken is ERC20, Ownable2Step, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Whether deposit operations are paused
bool public depositPaused;
/// @notice Whether redeem operations are paused
bool public redeemPaused;
/// @notice The underlying token that this LP token represents
IERC20 public underlying;
/// @notice The address of the credit vault contract
address public creditVault;
/// @notice The number of decimals for this token, matching the underlying token's decimals
uint8 private _decimals;
/// @notice Early withdrawal fee in basis points (1 bip = 0.01%)
/// @dev Applied to prevent front-running by users who deposit right before yield distribution and immediately redeem after
uint256 public earlyWithdrawFeeBips;
/// @notice Total amount of underlying assets deposited by LPs
uint256 public totalUnderlying;
/// @notice Total number of shares issued
uint256 public totalShares;
/// @notice Minimum time interval between deposit and redeem (in seconds)
uint256 public minRedeemInterval = 8 hours;
/// @notice Minimum amount required for deposits
uint256 public minDeposit;
/// @notice Mapping of user addresses to their share balances
mapping(address => uint256) public shares;
/// @notice Mapping of trusted operators who can call depositFor and redeemTo functions
mapping(address => bool) public trustedOperators;
/// @notice Mapping of user addresses to their last deposit timestamp
mapping(address => uint256) public lastDepositTimestamp;
/// @notice Mapping of addresses exempt from redeem cooldown period and early withdrawal fees
mapping(address => bool) public redeemCooldownExempt;
/*//////////////////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Event emitted when deposit operation is paused
event DepositPaused();
/// @notice Event emitted when deposit operation is unpaused
event DepositUnpaused();
/// @notice Event emitted when redeem operation is paused
event RedeemPaused();
/// @notice Event emitted when redeem operation is unpaused
event RedeemUnpaused();
/// @notice Event emitted when yield is distributed to LP holders
event YieldDistributed(uint256 yieldAmount);
/// @notice Event emitted when minimum redeem interval is updated
event MinRedeemIntervalUpdated(uint256 newInterval);
/// @notice Event emitted when shares are transferred between addresses
event TransferShares(address indexed from, address indexed to, uint256 shares);
/// @notice Event emitted when new shares are minted
event SharesMinted(address indexed from, address indexed to, uint256 shares, uint256 underlyingAmount);
/// @notice Event emitted when shares are burned
event SharesBurned(address indexed from, address indexed to, uint256 shares, uint256 underlyingAmount);
/// @notice Event emitted when minimum deposit amount is updated
event MinDepositUpdated(uint256 oldAmount, uint256 newAmount);
/// @notice Event emitted when early withdraw fee is updated
event EarlyWithdrawFeeBipsUpdated(uint256 oldFeeBips, uint256 newFeeBips);
/// @notice Event emitted when a trusted operator status is updated
event TrustedOperatorUpdated(address indexed account, bool status);
/// @notice Event emitted when an address's redeem cooldown exemption status is updated
event RedeemCooldownExemptUpdated(address indexed account, bool status);
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
address _underlying,
address _creditVault
) ERC20(_name, _symbol) {
underlying = IERC20(_underlying);
creditVault = _creditVault;
_decimals = IERC20(address(underlying)).decimals();
}
/// @notice Deposit underlying tokens to mint LP tokens
/// @param amount Amount of underlying tokens to deposit
/// @return sharesToMint Amount of LP tokens minted
function deposit(uint256 amount)
external
nonReentrant
whenNotPaused(depositPaused)
returns (uint256 sharesToMint)
{
sharesToMint = _deposit(msg.sender, msg.sender, amount);
}
/// @notice Deposit underlying tokens on behalf of another address
/// @param to The address to mint shares to
/// @param amount Amount of underlying tokens to deposit
/// @return sharesToMint Amount of LP tokens minted
function depositFor(
address to,
uint256 amount
) external nonReentrant whenNotPaused(depositPaused) returns (uint256 sharesToMint) {
require(to != address(0), ErrorsLib.ZeroAddress());
require(trustedOperators[msg.sender], ErrorsLib.NotTrustedOperator());
sharesToMint = _deposit(msg.sender, to, amount);
}
/// @notice Redeem LP tokens for underlying tokens
/// @param sharesToBurn Amount of LP tokens to burn
/// @return underlyingAmount Amount of underlying tokens received
function redeem(uint256 sharesToBurn)
external
nonReentrant
whenNotPaused(redeemPaused)
returns (uint256 underlyingAmount)
{
underlyingAmount = _redeem(sharesToBurn, msg.sender);
}
/// @notice Redeem LP tokens and send underlying tokens to a specified address
/// @param sharesToBurn Amount of LP tokens to burn from caller's balance
/// @param to Address that will receive the underlying tokens
/// @return underlyingAmount Amount of underlying tokens sent to the recipient
function redeemTo(
uint256 sharesToBurn,
address to
) external nonReentrant whenNotPaused(redeemPaused) returns (uint256 underlyingAmount) {
require(to != address(0), ErrorsLib.ZeroAddress());
require(trustedOperators[msg.sender], ErrorsLib.NotTrustedOperator());
underlyingAmount = _redeem(sharesToBurn, to);
}
/// @notice Transfers shares from sender to recipient
/// @param recipient The address to transfer shares to
/// @param sharesAmount The number of shares to transfer
/// @return The amount of underlying tokens the shares represent
function transferShares(address recipient, uint256 sharesAmount) external returns (uint256) {
_transferShares(msg.sender, recipient, sharesAmount);
uint256 tokensAmount = getUnderlyingByShares(sharesAmount);
_emitTransferEvents(msg.sender, recipient, tokensAmount, sharesAmount);
return tokensAmount;
}
/// @notice Distributes yield to LP token holders
/// @param yieldAmount Amount of yield to distribute
/// @dev Can only be called by the credit vault
function distributeYield(uint256 yieldAmount) external {
require(totalShares > 0, ErrorsLib.PoolNotInitialized());
require(yieldAmount > 0, ErrorsLib.NoYieldToDistribute());
require(msg.sender == creditVault, ErrorsLib.OnlyCreditVault());
totalUnderlying += yieldAmount;
emit YieldDistributed(yieldAmount);
}
/// @notice Gets the underlying token balance of an account
/// @param account The address to check the balance for
/// @return The amount of underlying tokens the account effectively owns
function balanceOf(address account) public view override returns (uint256) {
return getUnderlyingByShares(shares[account]);
}
/// @notice Gets the total supply of underlying tokens in the pool
/// @return The total amount of underlying tokens managed by this contract
function totalSupply() public view override returns (uint256) {
return totalUnderlying;
}
/// @notice Gets the number of shares owned by an account
/// @param account The address to check shares for
/// @return The number of shares owned by the account
function sharesOf(address account) public view returns (uint256) {
return shares[account];
}
/// @notice Calculates the underlying token amount for a given number of shares
/// @param sharesAmount The number of shares to convert
/// @return The corresponding amount of underlying tokens
function getUnderlyingByShares(uint256 sharesAmount) public view returns (uint256) {
if (totalShares == 0) {
return sharesAmount;
}
return (sharesAmount * totalUnderlying) / totalShares;
}
/// @notice Calculates the number of shares for a given amount of underlying tokens
/// @param underlyingAmount The amount of underlying tokens to convert
/// @return The corresponding number of shares
function getSharesByUnderlying(uint256 underlyingAmount) public view returns (uint256) {
if (totalShares == 0) {
return underlyingAmount;
}
return (underlyingAmount * totalShares) / totalUnderlying;
}
/// @notice Gets the current exchange rate between shares and underlying tokens
/// @return The exchange rate scaled by 1e18 (1:1 = 1e18)
function exchangeRate() public view returns (uint256) {
if (totalShares == 0) {
return 1e18; // Initial exchange rate 1:1
}
return (totalUnderlying * 1e18) / totalShares;
}
/// @notice Gets the number of decimals for this token
/// @return The number of decimals, matching the underlying token
function decimals() public view override returns (uint8) {
return _decimals;
}
/// @notice Sets the minimum deposit amount
/// @param _minDeposit New minimum deposit amount
/// @dev Can only be called by the owner
function setMinDeposit(uint256 _minDeposit) external onlyOwner {
uint256 oldAmount = minDeposit;
minDeposit = _minDeposit;
emit MinDepositUpdated(oldAmount, _minDeposit);
}
/// @notice Sets the minimum time interval required between deposit and redeem
/// @param _interval New minimum interval in seconds
/// @dev Can only be called by the owner
function setMinRedeemInterval(uint256 _interval) external onlyOwner {
minRedeemInterval = _interval;
emit MinRedeemIntervalUpdated(_interval);
}
/// @notice Sets the early withdrawal fee in basis points (BIPs)
/// @param _earlyWithdrawFeeBips New early withdrawal fee in BIPs
/// @dev Can only be called by the owner
function setEarlyWithdrawFeeBips(uint256 _earlyWithdrawFeeBips) external onlyOwner {
require(_earlyWithdrawFeeBips <= MAX_EARLY_WITHDRAW_FEE_BIPS, ErrorsLib.InvalidFeeBips());
uint256 oldFeeBips = earlyWithdrawFeeBips;
earlyWithdrawFeeBips = _earlyWithdrawFeeBips;
emit EarlyWithdrawFeeBipsUpdated(oldFeeBips, _earlyWithdrawFeeBips);
}
/// @notice Sets the trusted operator status for an address
/// @param account The address to update
/// @param status The new operator status
function setTrustedOperator(address account, bool status) external onlyOwner {
require(account != address(0), ErrorsLib.ZeroAddress());
trustedOperators[account] = status;
emit TrustedOperatorUpdated(account, status);
}
/// @notice Sets the redeem cooldown exemption status for an address
/// @param account The address to update
/// @param status The new exemption status
/// @dev Can only be called by the owner
function setRedeemCooldownExempt(address account, bool status) external onlyOwner {
require(account != address(0), ErrorsLib.ZeroAddress());
redeemCooldownExempt[account] = status;
emit RedeemCooldownExemptUpdated(account, status);
}
/*//////////////////////////////////////////////////////////////////////////
PAUSE OPERATIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Function to pause deposit operation
function pauseDeposit() external onlyOwner {
depositPaused = true;
emit DepositPaused();
}
/// @notice Function to unpause deposit operation
function unpauseDeposit() external onlyOwner {
depositPaused = false;
emit DepositUnpaused();
}
/// @notice Function to pause redeem operation
function pauseRedeem() external onlyOwner {
redeemPaused = true;
emit RedeemPaused();
}
/// @notice Function to unpause redeem operation
function unpauseRedeem() external onlyOwner {
redeemPaused = false;
emit RedeemUnpaused();
}
modifier whenNotPaused(bool feature) {
if (feature) {
revert ErrorsLib.FeaturePaused();
}
_;
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
function _deposit(address from, address to, uint256 amount) internal returns (uint256 sharesToMint) {
require(amount >= minDeposit && amount > 0, ErrorsLib.BelowMinimumDeposit());
// Transfer underlying to vault
uint256 balanceBefore = underlying.balanceOf(creditVault);
underlying.safeTransferFrom(from, creditVault, amount);
amount = underlying.balanceOf(creditVault) - balanceBefore;
// Calculate shares to mint
if (totalShares == 0) {
sharesToMint = amount; // Initial shares 1:1
} else {
sharesToMint = (amount * totalShares) / totalUnderlying;
}
// Mint shares
_mintShares(to, sharesToMint);
// Update total underlying
totalUnderlying += amount;
lastDepositTimestamp[to] = block.timestamp;
emit SharesMinted(from, to, sharesToMint, amount);
}
function _redeem(uint256 sharesToBurn, address to) internal returns (uint256 underlyingAmount) {
require(sharesToBurn > 0, ErrorsLib.ZeroAmount());
require(shares[msg.sender] >= sharesToBurn, ErrorsLib.InsufficientShares());
// Calculate underlying amount
underlyingAmount = (sharesToBurn * totalUnderlying) / totalShares;
if (
block.timestamp < lastDepositTimestamp[msg.sender] + minRedeemInterval && earlyWithdrawFeeBips > 0
&& !redeemCooldownExempt[msg.sender]
) {
underlyingAmount -= (underlyingAmount * earlyWithdrawFeeBips) / 10_000;
}
// Burn shares first
_burnShares(msg.sender, sharesToBurn);
// Transfer underlying from vault to msg.sender
uint256 balanceBefore = underlying.balanceOf(creditVault);
CreditVault(creditVault).pay(to, underlyingAmount);
underlyingAmount = balanceBefore - underlying.balanceOf(creditVault);
// Update total underlying
totalUnderlying -= underlyingAmount;
emit SharesBurned(msg.sender, to, sharesToBurn, underlyingAmount);
}
function _mintShares(address to, uint256 shareAmount) internal {
require(shareAmount > 0, ErrorsLib.ZeroAmount());
require(to != address(0), ErrorsLib.ZeroAddress());
shares[to] += shareAmount;
totalShares += shareAmount;
}
function _burnShares(address from, uint256 shareAmount) internal {
require(shareAmount > 0, ErrorsLib.ZeroAmount());
require(from != address(0), ErrorsLib.ZeroAddress());
shares[from] -= shareAmount;
totalShares -= shareAmount;
}
/// @notice Override ERC20's _transfer to handle yield-bearing LP token transfers
/// @dev Since this is a yield-bearing token, the actual transfer is done by transferring shares
/// rather than token amounts directly. The shares represent the user's proportion of the
/// total underlying assets including yield.
/// @param from The address to transfer from
/// @param to The address to transfer to
/// @param amount The underlying token amount to transfer
function _transfer(address from, address to, uint256 amount) internal override {
uint256 sharesToTransfer = getSharesByUnderlying(amount);
_transferShares(from, to, sharesToTransfer);
_emitTransferEvents(from, to, amount, sharesToTransfer);
}
function _transferShares(address from, address to, uint256 _shares) internal {
require(from != address(0) && to != address(0), ErrorsLib.ZeroAddress());
require(from != to, ErrorsLib.TransferSelf());
require(to != address(this), ErrorsLib.TransferToContract());
_validateTransferCooldown(from);
shares[from] -= _shares;
shares[to] += _shares;
}
function _validateTransferCooldown(address user) internal view {
// During cooldown period, user can't transfer shares, but can still redeem
require(
lastDepositTimestamp[user] + minRedeemInterval <= block.timestamp || redeemCooldownExempt[user],
ErrorsLib.TransferInCooldown()
);
}
function _emitTransferEvents(address from, address to, uint256 tokenAmount, uint256 sharesAmount) internal {
emit Transfer(from, to, tokenAmount);
emit TransferShares(from, to, sharesAmount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\\x19Ethereum Signed Message:\
32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\\x19\\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.8;
import "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(_FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.0;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return 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._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory 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._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory 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._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory 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._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
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 contract
require(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._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @title Transient storage utils
library TStorage {
/// @notice Loads a boolean value from transient storage at a given slot.
/// @param slot The storage slot to read from.
/// @return value The boolean value stored at the specified slot.
function tload(bytes32 slot) internal view returns (bool value) {
assembly {
value := tload(slot)
}
}
/// @notice Stores a boolean value in transient storage at a given slot.
/// @param slot The storage slot to write to.
/// @param value The boolean value to store at the specified slot.
function tstore(bytes32 slot, bool value) internal {
assembly {
tstore(slot, value)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/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.
*/
library SafeERC20 {
using Address for address;
/**
* @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.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
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, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation 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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (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, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== 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.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
File 4 of 4: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.18;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/