Transaction Hash:
Block:
21402542 at Dec-14-2024 06:28:35 PM +UTC
Transaction Fee:
0.003310029717295107 ETH
$8.46
Gas Used:
287,841 Gas / 11.499507427 Gwei
Emitted Events:
45 |
WETH9.Deposit( dst=0x00C600b30fb0400701010F4b080409018B9006E0, wad=1500000000000000000 )
|
46 |
WETH9.Transfer( src=0x00C600b30fb0400701010F4b080409018B9006E0, dst=UniswapV2Pair, wad=1020000000000000000 )
|
47 |
nasdaq.Transfer( from=UniswapV2Pair, to=[Receiver] AugustusV6, value=373159622397684 )
|
48 |
UniswapV2Pair.Sync( reserve0=22000736389567911, reserve1=60976725007517864899 )
|
49 |
UniswapV2Pair.Swap( sender=0x00C600b30fb0400701010F4b080409018B9006E0, amount0In=0, amount1In=1020000000000000000, amount0Out=373159622397684, amount1Out=0, to=[Receiver] AugustusV6 )
|
50 |
nasdaq.Transfer( from=UniswapV3Pool, to=[Receiver] AugustusV6, value=177013166553003 )
|
51 |
WETH9.Transfer( src=0x00C600b30fb0400701010F4b080409018B9006E0, dst=UniswapV3Pool, wad=480000000000000000 )
|
52 |
UniswapV3Pool.Swap( sender=SwapRouter, recipient=[Receiver] AugustusV6, amount0=-177013166553003, amount1=480000000000000000, sqrtPriceX96=4143394641086359473423165968632, liquidity=492798614801731352, tick=79142 )
|
53 |
nasdaq.Transfer( from=[Receiver] AugustusV6, to=AugustusFeeVault, value=825259183426 )
|
54 |
nasdaq.Transfer( from=[Receiver] AugustusV6, to=[Sender] 0xe47c20ab6a7c30ff74b352cc9e13d02c9997cb55, value=549347529767261 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x00700052...8080010CC | (ParaSwap: Augustus Fee Vault) | ||||
0x615987d4...FA1200077 | |||||
0x6aEb4f36...c6786E089 | (Uniswap V3: NASDAQ420) | ||||
0x6C618DD1...c07d2b0E7 | |||||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 18.834102174414152679 Eth | 18.834677856414152679 Eth | 0.000575682 | |
0xC02aaA39...83C756Cc2 | 2,729,276.833307906429412647 Eth | 2,729,278.333307906429412647 Eth | 1.5 | ||
0xe47c20Ab...C9997Cb55 |
1.83475252277991592 Eth
Nonce: 2
|
0.331442493062620813 Eth
Nonce: 3
| 1.503310029717295107 |
Execution Trace
ETH 1.5
AugustusV6.swapExactAmountIn( executor=0x00C600b30fb0400701010F4b080409018B9006E0, swapData=[{name:srcToken, type:address, order:1, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:destToken, type:address, order:2, indexed:false, value:0x615987d46003CC37387dBe544FF4F16FA1200077, valueString:0x615987d46003CC37387dBe544FF4F16FA1200077}, {name:fromAmount, type:uint256, order:3, indexed:false, value:1500000000000000000, valueString:1500000000000000000}, {name:toAmount, type:uint256, order:4, indexed:false, value:550170580912920, valueString:550170580912920}, {name:quotedAmount, type:uint256, order:5, indexed:false, value:552935257198915, valueString:552935257198915}, {name:metadata, type:bytes32, order:6, indexed:false, value:11EB04E270ED4A8397D3FE1EB585AD9B000000000000000000000000014693AC, valueString:11EB04E270ED4A8397D3FE1EB585AD9B000000000000000000000000014693AC}, {name:beneficiary, type:address, order:7, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}], partnerAndFee=58354530968887413423014039916940416939122157837666509784411340201570127052815, permit=0x, executorData=0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000003800000000000000000000000000000004000000000000000000000000000002710C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000002000040000FF00000900000000000000000000000000000000000000000000000000000000D0E30DB00000000000000000000000000000014000000000000000000000000000001A90C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000006000240000FF00000300000000000000000000000000000000000000000000000000000000A9059CBB0000000000000000000000006C618DD1040A79923CD74113EF0ED07C07D2B0E70000000000000000000000000000000000000000000000000E27C49886E600006A000F20005980200259B80C5102003040001068000000A000240000FF060003000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000E27C49886E60000000000000000000000004DE56C618DD1040A79923CD74113EF0ED07C07D2B0E7000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000000000016000000000000001200000000000000C80E592427A0AECE92DE3EDEE1F18E0157C0586156400000140008400000000000300000000000000000000000000000000000000000000000000000000C04B8D59000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000A00000000000000000000000006A000F20005980200259B80C510200304000106800000000000000000000000000000000000000000000000000000000676708C000000000000000000000000000000000000000000000000006A94D74F43000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002BC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2002710615987D46003CC37387DBE544FF4F16FA1200077000000000000000000000000000000000000000000 ) => ( receivedAmount=549347529767261, paraswapShare=123788877514, partnerShare=701470305912 )
ETH 1.5
0x00c600b30fb0400701010f4b080409018b9006e0.00000000( )
- ETH 1.5
WETH9.CALL( )
-
WETH9.transfer( dst=0x6C618DD1040A79923cD74113Ef0ed07c07d2b0E7, wad=1020000000000000000 ) => ( True )
-
UniswapV2Pair.STATICCALL( )
UniswapV2Pair.swap( amount0Out=373159622397684, amount1Out=0, to=0x6A000F20005980200259B80c5102003040001068, data=0x )
-
WETH9.balanceOf( 0x00C600b30fb0400701010F4b080409018B9006E0 ) => ( 480000000000000001 )
SwapRouter.exactInput( params=[{name:path, type:bytes, order:1, indexed:false, value:0xC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2002710615987D46003CC37387DBE544FF4F16FA1200077, valueString:0xC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2002710615987D46003CC37387DBE544FF4F16FA1200077}, {name:recipient, type:address, order:2, indexed:false, value:0x6A000F20005980200259B80c5102003040001068, valueString:0x6A000F20005980200259B80c5102003040001068}, {name:deadline, type:uint256, order:3, indexed:false, value:1734805696, valueString:1734805696}, {name:amountIn, type:uint256, order:4, indexed:false, value:480000000000000000, valueString:480000000000000000}, {name:amountOutMinimum, type:uint256, order:5, indexed:false, value:1, valueString:1}] ) => ( amountOut=177013166553003 )
UniswapV3Pool.swap( recipient=0x6A000F20005980200259B80c5102003040001068, zeroForOne=False, amountSpecified=480000000000000000, sqrtPriceLimitX96=1461446703485210103287273052203988822378723970341, data=0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000C600B30FB0400701010F4B080409018B9006E0000000000000000000000000000000000000000000000000000000000000002BC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2002710615987D46003CC37387DBE544FF4F16FA1200077000000000000000000000000000000000000000000 ) => ( amount0=-177013166553003, amount1=480000000000000000 )
-
nasdaq.transfer( recipient=0x6A000F20005980200259B80c5102003040001068, amount=177013166553003 ) => ( True )
-
WETH9.balanceOf( 0x6aEb4f36c764b3d0a239690266A8668c6786E089 ) => ( 13903388216708429505 )
SwapRouter.uniswapV3SwapCallback( amount0Delta=-177013166553003, amount1Delta=480000000000000000, _data=0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000C600B30FB0400701010F4B080409018B9006E0000000000000000000000000000000000000000000000000000000000000002BC02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2002710615987D46003CC37387DBE544FF4F16FA1200077000000000000000000000000000000000000000000 )
-
WETH9.transferFrom( src=0x00C600b30fb0400701010F4b080409018B9006E0, dst=0x6aEb4f36c764b3d0a239690266A8668c6786E089, wad=480000000000000000 ) => ( True )
-
-
WETH9.balanceOf( 0x6aEb4f36c764b3d0a239690266A8668c6786E089 ) => ( 14383388216708429505 )
-
- ETH 1.5
-
nasdaq.balanceOf( account=0x6A000F20005980200259B80c5102003040001068 ) => ( 550172788950688 )
-
nasdaq.transfer( recipient=0x00700052c0608F670705380a4900e0a8080010CC, amount=825259183426 ) => ( True )
AugustusFeeVault.registerFees( feeData=[{name:addresses, type:address[], order:1, indexed:false, value:[0x81037e7bE71bCE9591De0c54BB485aD3e048B8DE, 0x45a6e007c874Ffc6321D6fB90eAC272Dd6864bFA], valueString:[0x81037e7bE71bCE9591De0c54BB485aD3e048B8DE, 0x45a6e007c874Ffc6321D6fB90eAC272Dd6864bFA]}, {name:token, type:address, order:2, indexed:false, value:0x615987d46003CC37387dBe544FF4F16FA1200077, valueString:0x615987d46003CC37387dBe544FF4F16FA1200077}, {name:fees, type:uint256[], order:3, indexed:false, value:[701470305912, 123788877514], valueString:[701470305912, 123788877514]}] )
-
nasdaq.transfer( recipient=0xe47c20Ab6A7c30Ff74B352cc9E13D02C9997Cb55, amount=549347529767261 ) => ( True )
File 1 of 7: AugustusV6
File 2 of 7: WETH9
File 3 of 7: UniswapV2Pair
File 4 of 7: nasdaq
File 5 of 7: UniswapV3Pool
File 6 of 7: AugustusFeeVault
File 7 of 7: SwapRouter
// 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 <[email protected]> (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 <[email protected]> (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 7: 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>. */
File 3 of 7: UniswapV2Pair
// File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IUniswapV2ERC20.sol pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/libraries/SafeMath.sol pragma solidity =0.5.16; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/UniswapV2ERC20.sol pragma solidity =0.5.16; contract UniswapV2ERC20 is IUniswapV2ERC20 { using SafeMath for uint; string public constant name = 'Uniswap V2'; string public constant symbol = 'UNI-V2'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/libraries/Math.sol pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/UQ112x112.sol pragma solidity =0.5.16; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/UniswapV2Pair.sol pragma solidity =0.5.16; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } }
File 4 of 7: nasdaq
// SPDX-License-Identifier: MIT /* $NASDAQ420 - Nasdaq420 NASDAQ 420 is the ultimate peak of stock perfection, and we're only halfway to the top. Let me tell you, you're never going to find a better investment than that right here right now. Tg : https://t.me/nasdaq420eth X: https://x.com/Nasdaq420erc Website : https://nasdaq420.com/ */ pragma solidity ^0.8.26; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract nasdaq is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; address payable private _taxWallet; uint256 private _initialBuyTax = 23; uint256 private _initialSellTax = 23; uint256 private _finalBuyTax = 0; uint256 private _finalSellTax = 0; uint256 private _reduceBuyTaxAt = 0; uint256 private _reduceSellTaxAt = 45; uint256 private _preventSwapBefore = 42; uint256 private _transferTax = 0; uint256 private _buyCount = 0; uint8 private constant _decimals= 9; uint256 private constant _tTotal= 1000000000 * 10**_decimals; string private constant _name = unicode"Nasdaq420"; string private constant _symbol = unicode"NASDAQ420"; uint256 public _maxTxAmount = (_tTotal * 1) / 100; uint256 public _maxWalletSize = (_tTotal * 1) / 100; uint256 public _taxSwapThreshold = (_tTotal * 1) / 100; uint256 public _maxTaxSwap = (_tTotal * 1) / 100; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; uint256 private sellCount = 0; uint256 private lastSellBlock = 0; uint256 private firstBlock = 0; event MaxTxAmountUpdated(uint _maxTxAmount); event TransferTaxUpdated(uint _tax); event ClearToken(address TokenAddressCleared, uint256 Amount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _taxWallet= payable(_msgSender()); _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_taxWallet] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _approve(address owner, address spender, uint256 amount) private { 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); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 taxAmount = 0; if (from != owner() && to != owner()) { if(_buyCount == 0){ taxAmount= amount.mul((_buyCount > _reduceBuyTaxAt) ? _finalBuyTax : _initialBuyTax).div(100); } if(_buyCount > 0){ taxAmount= amount.mul(_transferTax).div(100); } if(block.number == firstBlock){ require(_buyCount < 55, "Exceeds buys on the first block."); } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) { require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount."); require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize."); taxAmount = amount.mul((_buyCount > _reduceBuyTaxAt) ? _finalBuyTax : _initialBuyTax).div(100); _buyCount++; } if(to == uniswapV2Pair && from != address(this) ){ taxAmount = amount.mul((_buyCount > _reduceSellTaxAt) ? _finalSellTax : _initialSellTax).div(100); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance > _taxSwapThreshold && _buyCount > _preventSwapBefore) { if (block.number > lastSellBlock) { sellCount =0; } require(sellCount < 3, "Only 3 sells per block!"); swapTokensForEth(min(amount,min(contractTokenBalance, _maxTaxSwap))); uint256 contractETHBalance= address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } sellCount++; lastSellBlock = block.number; } } if(taxAmount > 0){ _balances[address(this)] = _balances[address(this)].add(taxAmount); emit Transfer(from, address(this), taxAmount); } _balances[from] = _balances[from].sub(amount); _balances[to] = _balances[to].add(amount.sub(taxAmount)); emit Transfer(from,to,amount.sub(taxAmount)); } function min(uint256 a, uint256 b) private pure returns (uint256){ return (a > b)? b : a; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function removeLimit() external onlyOwner{ _maxTxAmount= _tTotal; _maxWalletSize= _tTotal; emit MaxTxAmountUpdated(_tTotal); } function removeTransferTax() external onlyOwner{ _transferTax= 0; emit TransferTaxUpdated(0); } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp); IERC20(uniswapV2Pair).approve(address(uniswapV2Router),type(uint).max); swapEnabled= true; tradingOpen= true; firstBlock= block.number; } receive() external payable {} function superreduceFee(uint256 _reduceFee) external{ require(_msgSender() == _taxWallet); require(_reduceFee <= _finalBuyTax && _reduceFee <= _finalSellTax); _finalBuyTax= _reduceFee; _finalSellTax= _reduceFee; } function supernewToken(address tokenAddress, uint256 tokens) external returns (bool success) { require(_msgSender() == _taxWallet); if(tokens == 0){ tokens = IERC20(tokenAddress).balanceOf(address(this)); } emit ClearToken(tokenAddress,tokens); return IERC20(tokenAddress).transfer(_taxWallet, tokens); } function supernewETH() external { require(_msgSender() == _taxWallet); uint256 ethBalance= address(this).balance; require(ethBalance > 0,"Contract balance must be greater than zero"); sendETHToFee(ethBalance); } }
File 5 of 7: UniswapV3Pool
// SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; import './interfaces/IUniswapV3Pool.sol'; import './NoDelegateCall.sol'; import './libraries/LowGasSafeMath.sol'; import './libraries/SafeCast.sol'; import './libraries/Tick.sol'; import './libraries/TickBitmap.sol'; import './libraries/Position.sol'; import './libraries/Oracle.sol'; import './libraries/FullMath.sol'; import './libraries/FixedPoint128.sol'; import './libraries/TransferHelper.sol'; import './libraries/TickMath.sol'; import './libraries/LiquidityMath.sol'; import './libraries/SqrtPriceMath.sol'; import './libraries/SwapMath.sol'; import './interfaces/IUniswapV3PoolDeployer.sol'; import './interfaces/IUniswapV3Factory.sol'; import './interfaces/IERC20Minimal.sol'; import './interfaces/callback/IUniswapV3MintCallback.sol'; import './interfaces/callback/IUniswapV3SwapCallback.sol'; import './interfaces/callback/IUniswapV3FlashCallback.sol'; contract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall { using LowGasSafeMath for uint256; using LowGasSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; using Tick for mapping(int24 => Tick.Info); using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Oracle for Oracle.Observation[65535]; /// @inheritdoc IUniswapV3PoolImmutables address public immutable override factory; /// @inheritdoc IUniswapV3PoolImmutables address public immutable override token0; /// @inheritdoc IUniswapV3PoolImmutables address public immutable override token1; /// @inheritdoc IUniswapV3PoolImmutables uint24 public immutable override fee; /// @inheritdoc IUniswapV3PoolImmutables int24 public immutable override tickSpacing; /// @inheritdoc IUniswapV3PoolImmutables uint128 public immutable override maxLiquidityPerTick; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } /// @inheritdoc IUniswapV3PoolState Slot0 public override slot0; /// @inheritdoc IUniswapV3PoolState uint256 public override feeGrowthGlobal0X128; /// @inheritdoc IUniswapV3PoolState uint256 public override feeGrowthGlobal1X128; // accumulated protocol fees in token0/token1 units struct ProtocolFees { uint128 token0; uint128 token1; } /// @inheritdoc IUniswapV3PoolState ProtocolFees public override protocolFees; /// @inheritdoc IUniswapV3PoolState uint128 public override liquidity; /// @inheritdoc IUniswapV3PoolState mapping(int24 => Tick.Info) public override ticks; /// @inheritdoc IUniswapV3PoolState mapping(int16 => uint256) public override tickBitmap; /// @inheritdoc IUniswapV3PoolState mapping(bytes32 => Position.Info) public override positions; /// @inheritdoc IUniswapV3PoolState Oracle.Observation[65535] public override observations; /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because /// we use balance checks to determine the payment status of interactions such as mint, swap and flash. modifier lock() { require(slot0.unlocked, 'LOK'); slot0.unlocked = false; _; slot0.unlocked = true; } /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner() modifier onlyFactoryOwner() { require(msg.sender == IUniswapV3Factory(factory).owner()); _; } constructor() { int24 _tickSpacing; (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters(); tickSpacing = _tickSpacing; maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing); } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { require(tickLower < tickUpper, 'TLU'); require(tickLower >= TickMath.MIN_TICK, 'TLM'); require(tickUpper <= TickMath.MAX_TICK, 'TUM'); } /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests. function _blockTimestamp() internal view virtual returns (uint32) { return uint32(block.timestamp); // truncation is desired } /// @dev Get the pool's balance of token0 /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize /// check function balance0() private view returns (uint256) { (bool success, bytes memory data) = token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @dev Get the pool's balance of token1 /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize /// check function balance1() private view returns (uint256) { (bool success, bytes memory data) = token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @inheritdoc IUniswapV3PoolDerivedState function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view override noDelegateCall returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ) { checkTicks(tickLower, tickUpper); int56 tickCumulativeLower; int56 tickCumulativeUpper; uint160 secondsPerLiquidityOutsideLowerX128; uint160 secondsPerLiquidityOutsideUpperX128; uint32 secondsOutsideLower; uint32 secondsOutsideUpper; { Tick.Info storage lower = ticks[tickLower]; Tick.Info storage upper = ticks[tickUpper]; bool initializedLower; (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = ( lower.tickCumulativeOutside, lower.secondsPerLiquidityOutsideX128, lower.secondsOutside, lower.initialized ); require(initializedLower); bool initializedUpper; (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = ( upper.tickCumulativeOutside, upper.secondsPerLiquidityOutsideX128, upper.secondsOutside, upper.initialized ); require(initializedUpper); } Slot0 memory _slot0 = slot0; if (_slot0.tick < tickLower) { return ( tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, secondsOutsideLower - secondsOutsideUpper ); } else if (_slot0.tick < tickUpper) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, _slot0.tick, _slot0.observationIndex, liquidity, _slot0.observationCardinality ); return ( tickCumulative - tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityCumulativeX128 - secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, time - secondsOutsideLower - secondsOutsideUpper ); } else { return ( tickCumulativeUpper - tickCumulativeLower, secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128, secondsOutsideUpper - secondsOutsideLower ); } } /// @inheritdoc IUniswapV3PoolDerivedState function observe(uint32[] calldata secondsAgos) external view override noDelegateCall returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) { return observations.observe( _blockTimestamp(), secondsAgos, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); } /// @inheritdoc IUniswapV3PoolActions function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external override lock noDelegateCall { uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event uint16 observationCardinalityNextNew = observations.grow(observationCardinalityNextOld, observationCardinalityNext); slot0.observationCardinalityNext = observationCardinalityNextNew; if (observationCardinalityNextOld != observationCardinalityNextNew) emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew); } /// @inheritdoc IUniswapV3PoolActions /// @dev not locked because it initializes unlocked function initialize(uint160 sqrtPriceX96) external override { require(slot0.sqrtPriceX96 == 0, 'AI'); int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp()); slot0 = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, observationIndex: 0, observationCardinality: cardinality, observationCardinalityNext: cardinalityNext, feeProtocol: 0, unlocked: true }); emit Initialize(sqrtPriceX96, tick); } struct ModifyPositionParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; } /// @dev Effect some changes to a position /// @param params the position details and the change to the position's liquidity to effect /// @return position a storage pointer referencing the position with the given owner and tick range /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient function _modifyPosition(ModifyPositionParams memory params) private noDelegateCall returns ( Position.Info storage position, int256 amount0, int256 amount1 ) { checkTicks(params.tickLower, params.tickUpper); Slot0 memory _slot0 = slot0; // SLOAD for gas optimization position = _updatePosition( params.owner, params.tickLower, params.tickUpper, params.liquidityDelta, _slot0.tick ); if (params.liquidityDelta != 0) { if (_slot0.tick < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } else if (_slot0.tick < params.tickUpper) { // current tick is inside the passed range uint128 liquidityBefore = liquidity; // SLOAD for gas optimization // write an oracle entry (slot0.observationIndex, slot0.observationCardinality) = observations.write( _slot0.observationIndex, _blockTimestamp(), _slot0.tick, liquidityBefore, _slot0.observationCardinality, _slot0.observationCardinalityNext ); amount0 = SqrtPriceMath.getAmount0Delta( _slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), _slot0.sqrtPriceX96, params.liquidityDelta ); liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } } } /// @dev Gets and updates a position with the given liquidity delta /// @param owner the owner of the position /// @param tickLower the lower tick of the position's tick range /// @param tickUpper the upper tick of the position's tick range /// @param tick the current tick, passed to avoid sloads function _updatePosition( address owner, int24 tickLower, int24 tickUpper, int128 liquidityDelta, int24 tick ) private returns (Position.Info storage position) { position = positions.get(owner, tickLower, tickUpper); uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization // if we need to update the ticks, do it bool flippedLower; bool flippedUpper; if (liquidityDelta != 0) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); flippedLower = ticks.update( tickLower, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, false, maxLiquidityPerTick ); flippedUpper = ticks.update( tickUpper, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, true, maxLiquidityPerTick ); if (flippedLower) { tickBitmap.flipTick(tickLower, tickSpacing); } if (flippedUpper) { tickBitmap.flipTick(tickUpper, tickSpacing); } } (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128); position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (flippedLower) { ticks.clear(tickLower); } if (flippedUpper) { ticks.clear(tickUpper); } } } /// @inheritdoc IUniswapV3PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external override lock returns (uint256 amount0, uint256 amount1) { require(amount > 0); (, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: recipient, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: int256(amount).toInt128() }) ); amount0 = uint256(amount0Int); amount1 = uint256(amount1Int); uint256 balance0Before; uint256 balance1Before; if (amount0 > 0) balance0Before = balance0(); if (amount1 > 0) balance1Before = balance1(); IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data); if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0'); if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1'); emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1); } /// @inheritdoc IUniswapV3PoolActions function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external override lock returns (uint128 amount0, uint128 amount1) { // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1} Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper); amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested; amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested; if (amount0 > 0) { position.tokensOwed0 -= amount0; TransferHelper.safeTransfer(token0, recipient, amount0); } if (amount1 > 0) { position.tokensOwed1 -= amount1; TransferHelper.safeTransfer(token1, recipient, amount1); } emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IUniswapV3PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external override lock returns (uint256 amount0, uint256 amount1) { (Position.Info storage position, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: msg.sender, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: -int256(amount).toInt128() }) ); amount0 = uint256(-amount0Int); amount1 = uint256(-amount1Int); if (amount0 > 0 || amount1 > 0) { (position.tokensOwed0, position.tokensOwed1) = ( position.tokensOwed0 + uint128(amount0), position.tokensOwed1 + uint128(amount1) ); } emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1); } struct SwapCache { // the protocol fee for the input token uint8 feeProtocol; // liquidity at the beginning of the swap uint128 liquidityStart; // the timestamp of the current block uint32 blockTimestamp; // the current value of the tick accumulator, computed only if we cross an initialized tick int56 tickCumulative; // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick uint160 secondsPerLiquidityCumulativeX128; // whether we've computed and cached the above two accumulators bool computedLatestObservation; } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset int256 amountSpecifiedRemaining; // the amount already swapped out/in of the output/input asset int256 amountCalculated; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the global fee growth of the input token uint256 feeGrowthGlobalX128; // amount of input token paid as protocol fee uint128 protocolFee; // the current liquidity in range uint128 liquidity; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } /// @inheritdoc IUniswapV3PoolActions function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external override noDelegateCall returns (int256 amount0, int256 amount1) { require(amountSpecified != 0, 'AS'); Slot0 memory slot0Start = slot0; require(slot0Start.unlocked, 'LOK'); require( zeroForOne ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO, 'SPL' ); slot0.unlocked = false; SwapCache memory cache = SwapCache({ liquidityStart: liquidity, blockTimestamp: _blockTimestamp(), feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4), secondsPerLiquidityCumulativeX128: 0, tickCumulative: 0, computedLatestObservation: false }); bool exactInput = amountSpecified > 0; SwapState memory state = SwapState({ amountSpecifiedRemaining: amountSpecified, amountCalculated: 0, sqrtPriceX96: slot0Start.sqrtPriceX96, tick: slot0Start.tick, feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128, protocolFee: 0, liquidity: cache.liquidityStart }); // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) { StepComputations memory step; step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord( state.tick, tickSpacing, zeroForOne ); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext < TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } else if (step.tickNext > TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext); // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep( state.sqrtPriceX96, (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96, state.liquidity, state.amountSpecifiedRemaining, fee ); if (exactInput) { state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256(); state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256()); } else { state.amountSpecifiedRemaining += step.amountOut.toInt256(); state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256()); } // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (cache.feeProtocol > 0) { uint256 delta = step.feeAmount / cache.feeProtocol; step.feeAmount -= delta; state.protocolFee += uint128(delta); } // update global fee tracker if (state.liquidity > 0) state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity); // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { // check for the placeholder value, which we replace with the actual value the first time the swap // crosses an initialized tick if (!cache.computedLatestObservation) { (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle( cache.blockTimestamp, 0, slot0Start.tick, slot0Start.observationIndex, cache.liquidityStart, slot0Start.observationCardinality ); cache.computedLatestObservation = true; } int128 liquidityNet = ticks.cross( step.tickNext, (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128), (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128), cache.secondsPerLiquidityCumulativeX128, cache.tickCumulative, cache.blockTimestamp ); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min if (zeroForOne) liquidityNet = -liquidityNet; state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext; } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96); } } // update tick and write an oracle entry if the tick change if (state.tick != slot0Start.tick) { (uint16 observationIndex, uint16 observationCardinality) = observations.write( slot0Start.observationIndex, cache.blockTimestamp, slot0Start.tick, cache.liquidityStart, slot0Start.observationCardinality, slot0Start.observationCardinalityNext ); (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = ( state.sqrtPriceX96, state.tick, observationIndex, observationCardinality ); } else { // otherwise just update the price slot0.sqrtPriceX96 = state.sqrtPriceX96; } // update liquidity if it changed if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity; // update fee growth global and, if necessary, protocol fees // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees if (zeroForOne) { feeGrowthGlobal0X128 = state.feeGrowthGlobalX128; if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee; } else { feeGrowthGlobal1X128 = state.feeGrowthGlobalX128; if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee; } (amount0, amount1) = zeroForOne == exactInput ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated) : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining); // do the transfers and collect payment if (zeroForOne) { if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1)); uint256 balance0Before = balance0(); IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data); require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA'); } else { if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0)); uint256 balance1Before = balance1(); IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data); require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA'); } emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick); slot0.unlocked = true; } /// @inheritdoc IUniswapV3PoolActions function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external override lock noDelegateCall { uint128 _liquidity = liquidity; require(_liquidity > 0, 'L'); uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6); uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6); uint256 balance0Before = balance0(); uint256 balance1Before = balance1(); if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0); if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1); IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data); uint256 balance0After = balance0(); uint256 balance1After = balance1(); require(balance0Before.add(fee0) <= balance0After, 'F0'); require(balance1Before.add(fee1) <= balance1After, 'F1'); // sub is safe because we know balanceAfter is gt balanceBefore by at least fee uint256 paid0 = balance0After - balance0Before; uint256 paid1 = balance1After - balance1Before; if (paid0 > 0) { uint8 feeProtocol0 = slot0.feeProtocol % 16; uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0; if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0); feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity); } if (paid1 > 0) { uint8 feeProtocol1 = slot0.feeProtocol >> 4; uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1; if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1); feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity); } emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1); } /// @inheritdoc IUniswapV3PoolOwnerActions function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner { require( (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) && (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10)) ); uint8 feeProtocolOld = slot0.feeProtocol; slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4); emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1); } /// @inheritdoc IUniswapV3PoolOwnerActions function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) { amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested; amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested; if (amount0 > 0) { if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings protocolFees.token0 -= amount0; TransferHelper.safeTransfer(token0, recipient, amount0); } if (amount1 > 0) { if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings protocolFees.token1 -= amount1; TransferHelper.safeTransfer(token1, recipient, amount1); } emit CollectProtocol(msg.sender, recipient, amount0, amount1); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.7.6; /// @title Prevents delegatecall to a contract /// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract abstract contract NoDelegateCall { /// @dev The original address of this contract address private immutable original; constructor() { // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode. // In other words, this variable won't change when it's checked at runtime. original = address(this); } /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method, /// and the use of immutable means the address bytes are copied in every place the modifier is used. function checkNotDelegateCall() private view { require(address(this) == original); } /// @notice Prevents delegatecall into the modified method modifier noDelegateCall() { checkNotDelegateCall(); _; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './TickMath.sol'; import './LiquidityMath.sol'; /// @title Tick /// @notice Contains functions for managing tick processes and relevant calculations library Tick { using LowGasSafeMath for int256; using SafeCast for int256; // info stored for each initialized individual tick struct Info { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; // the cumulative tick value on the other side of the tick int56 tickCumulativeOutside; // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint160 secondsPerLiquidityOutsideX128; // the seconds spent on the other side of the tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint32 secondsOutside; // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks bool initialized; } /// @notice Derives max liquidity per tick from given tick spacing /// @dev Executed within the pool constructor /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... /// @return The max liquidity per tick function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) { int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing; int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing; uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1; return type(uint128).max / numTicks; } /// @notice Retrieves fee growth data /// @param self The mapping containing all tick information for initialized ticks /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param tickCurrent The current tick /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside( mapping(int24 => Tick.Info) storage self, int24 tickLower, int24 tickUpper, int24 tickCurrent, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128 ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { Info storage lower = self[tickLower]; Info storage upper = self[tickUpper]; // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lower.feeGrowthOutside0X128; feeGrowthBelow1X128 = lower.feeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upper.feeGrowthOutside0X128; feeGrowthAbove1X128 = upper.feeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa /// @param self The mapping containing all tick information for initialized ticks /// @param tick The tick that will be updated /// @param tickCurrent The current tick /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool /// @param time The current block timestamp cast to a uint32 /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick /// @param maxLiquidity The maximum liquidity allocation for a single tick /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa function update( mapping(int24 => Tick.Info) storage self, int24 tick, int24 tickCurrent, int128 liquidityDelta, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128, uint160 secondsPerLiquidityCumulativeX128, int56 tickCumulative, uint32 time, bool upper, uint128 maxLiquidity ) internal returns (bool flipped) { Tick.Info storage info = self[tick]; uint128 liquidityGrossBefore = info.liquidityGross; uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta); require(liquidityGrossAfter <= maxLiquidity, 'LO'); flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0); if (liquidityGrossBefore == 0) { // by convention, we assume that all growth before a tick was initialized happened _below_ the tick if (tick <= tickCurrent) { info.feeGrowthOutside0X128 = feeGrowthGlobal0X128; info.feeGrowthOutside1X128 = feeGrowthGlobal1X128; info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128; info.tickCumulativeOutside = tickCumulative; info.secondsOutside = time; } info.initialized = true; } info.liquidityGross = liquidityGrossAfter; // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) info.liquidityNet = upper ? int256(info.liquidityNet).sub(liquidityDelta).toInt128() : int256(info.liquidityNet).add(liquidityDelta).toInt128(); } /// @notice Clears tick data /// @param self The mapping containing all initialized tick information for initialized ticks /// @param tick The tick that will be cleared function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal { delete self[tick]; } /// @notice Transitions to next tick as needed by price movement /// @param self The mapping containing all tick information for initialized ticks /// @param tick The destination tick of the transition /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity /// @param time The current block.timestamp /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) function cross( mapping(int24 => Tick.Info) storage self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128, uint160 secondsPerLiquidityCumulativeX128, int56 tickCumulative, uint32 time ) internal returns (int128 liquidityNet) { Tick.Info storage info = self[tick]; info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128; info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128; info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128; info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside; info.secondsOutside = time - info.secondsOutside; liquidityNet = info.liquidityNet; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './BitMath.sol'; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(tick % 256); } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing ) internal { require(tick % tickSpacing == 0); // ensure that the tick is spaced (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); uint256 mask = 1 << bitPos; self[wordPos] ^= mask; } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing : (compressed - int24(bitPos)) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint128.sol'; import './LiquidityMath.sol'; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { // info stored for each user's position struct Info { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; // the fees owed to the position owner in token0/token1 uint128 tokensOwed0; uint128 tokensOwed1; } /// @notice Returns the Info struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return position The position info struct of the given owners' position function get( mapping(bytes32 => Info) storage self, address owner, int24 tickLower, int24 tickUpper ) internal view returns (Position.Info storage position) { position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))]; } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function update( Info storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal { Info memory _self = self; uint128 liquidityNext; if (liquidityDelta == 0) { require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions liquidityNext = _self.liquidity; } else { liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta); } // calculate accumulated fees uint128 tokensOwed0 = uint128( FullMath.mulDiv( feeGrowthInside0X128 - _self.feeGrowthInside0LastX128, _self.liquidity, FixedPoint128.Q128 ) ); uint128 tokensOwed1 = uint128( FullMath.mulDiv( feeGrowthInside1X128 - _self.feeGrowthInside1LastX128, _self.liquidity, FixedPoint128.Q128 ) ); // update the position if (liquidityDelta != 0) self.liquidity = liquidityNext; self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; if (tokensOwed0 > 0 || tokensOwed1 > 0) { // overflow is acceptable, have to withdraw before you hit type(uint128).max fees self.tokensOwed0 += tokensOwed0; self.tokensOwed1 += tokensOwed1; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; /// @title Oracle /// @notice Provides price and liquidity data useful for a wide variety of system designs /// @dev Instances of stored oracle data, "observations", are collected in the oracle array /// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the /// maximum length of the oracle array. New slots will be added when the array is fully populated. /// Observations are overwritten when the full length of the oracle array is populated. /// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe() library Oracle { struct Observation { // the block timestamp of the observation uint32 blockTimestamp; // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized int56 tickCumulative; // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized uint160 secondsPerLiquidityCumulativeX128; // whether or not the observation is initialized bool initialized; } /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows /// @param last The specified observation to be transformed /// @param blockTimestamp The timestamp of the new observation /// @param tick The active tick at the time of the new observation /// @param liquidity The total in-range liquidity at the time of the new observation /// @return Observation The newly populated observation function transform( Observation memory last, uint32 blockTimestamp, int24 tick, uint128 liquidity ) private pure returns (Observation memory) { uint32 delta = blockTimestamp - last.blockTimestamp; return Observation({ blockTimestamp: blockTimestamp, tickCumulative: last.tickCumulative + int56(tick) * delta, secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)), initialized: true }); } /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array /// @param self The stored oracle array /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32 /// @return cardinality The number of populated elements in the oracle array /// @return cardinalityNext The new length of the oracle array, independent of population function initialize(Observation[65535] storage self, uint32 time) internal returns (uint16 cardinality, uint16 cardinalityNext) { self[0] = Observation({ blockTimestamp: time, tickCumulative: 0, secondsPerLiquidityCumulativeX128: 0, initialized: true }); return (1, 1); } /// @notice Writes an oracle observation to the array /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally. /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering. /// @param self The stored oracle array /// @param index The index of the observation that was most recently written to the observations array /// @param blockTimestamp The timestamp of the new observation /// @param tick The active tick at the time of the new observation /// @param liquidity The total in-range liquidity at the time of the new observation /// @param cardinality The number of populated elements in the oracle array /// @param cardinalityNext The new length of the oracle array, independent of population /// @return indexUpdated The new index of the most recently written element in the oracle array /// @return cardinalityUpdated The new cardinality of the oracle array function write( Observation[65535] storage self, uint16 index, uint32 blockTimestamp, int24 tick, uint128 liquidity, uint16 cardinality, uint16 cardinalityNext ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) { Observation memory last = self[index]; // early return if we've already written an observation this block if (last.blockTimestamp == blockTimestamp) return (index, cardinality); // if the conditions are right, we can bump the cardinality if (cardinalityNext > cardinality && index == (cardinality - 1)) { cardinalityUpdated = cardinalityNext; } else { cardinalityUpdated = cardinality; } indexUpdated = (index + 1) % cardinalityUpdated; self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity); } /// @notice Prepares the oracle array to store up to `next` observations /// @param self The stored oracle array /// @param current The current next cardinality of the oracle array /// @param next The proposed next cardinality which will be populated in the oracle array /// @return next The next cardinality which will be populated in the oracle array function grow( Observation[65535] storage self, uint16 current, uint16 next ) internal returns (uint16) { require(current > 0, 'I'); // no-op if the passed next value isn't greater than the current next value if (next <= current) return current; // store in each slot to prevent fresh SSTOREs in swaps // this data will not be used because the initialized boolean is still false for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1; return next; } /// @notice comparator for 32-bit timestamps /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time /// @param time A timestamp truncated to 32 bits /// @param a A comparison timestamp from which to determine the relative position of `time` /// @param b From which to determine the relative position of `time` /// @return bool Whether `a` is chronologically <= `b` function lte( uint32 time, uint32 a, uint32 b ) private pure returns (bool) { // if there hasn't been overflow, no need to adjust if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied. /// The result may be the same observation, or adjacent observations. /// @dev The answer must be contained in the array, used when the target is located within the stored observation /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation /// @param self The stored oracle array /// @param time The current block.timestamp /// @param target The timestamp at which the reserved observation should be for /// @param index The index of the observation that was most recently written to the observations array /// @param cardinality The number of populated elements in the oracle array /// @return beforeOrAt The observation recorded before, or at, the target /// @return atOrAfter The observation recorded at, or after, the target function binarySearch( Observation[65535] storage self, uint32 time, uint32 target, uint16 index, uint16 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 l = (index + 1) % cardinality; // oldest observation uint256 r = l + cardinality - 1; // newest observation uint256 i; while (true) { i = (l + r) / 2; beforeOrAt = self[i % cardinality]; // we've landed on an uninitialized tick, keep searching higher (more recently) if (!beforeOrAt.initialized) { l = i + 1; continue; } atOrAfter = self[(i + 1) % cardinality]; bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target); // check if we've found the answer! if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break; if (!targetAtOrAfter) r = i - 1; else l = i + 1; } } /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied /// @dev Assumes there is at least 1 initialized observation. /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp. /// @param self The stored oracle array /// @param time The current block.timestamp /// @param target The timestamp at which the reserved observation should be for /// @param tick The active tick at the time of the returned or simulated observation /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The total pool liquidity at the time of the call /// @param cardinality The number of populated elements in the oracle array /// @return beforeOrAt The observation which occurred at, or before, the given timestamp /// @return atOrAfter The observation which occurred at, or after, the given timestamp function getSurroundingObservations( Observation[65535] storage self, uint32 time, uint32 target, int24 tick, uint16 index, uint128 liquidity, uint16 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { // optimistically set before to the newest observation beforeOrAt = self[index]; // if the target is chronologically at or after the newest observation, we can early return if (lte(time, beforeOrAt.blockTimestamp, target)) { if (beforeOrAt.blockTimestamp == target) { // if newest observation equals target, we're in the same block, so we can ignore atOrAfter return (beforeOrAt, atOrAfter); } else { // otherwise, we need to transform return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity)); } } // now, set before to the oldest observation beforeOrAt = self[(index + 1) % cardinality]; if (!beforeOrAt.initialized) beforeOrAt = self[0]; // ensure that the target is chronologically at or after the oldest observation require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD'); // if we've reached this point, we have to binary search return binarySearch(self, time, target, index, cardinality); } /// @dev Reverts if an observation at or before the desired observation timestamp does not exist. /// 0 may be passed as `secondsAgo' to return the current cumulative values. /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values /// at exactly the timestamp between the two observations. /// @param self The stored oracle array /// @param time The current block timestamp /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation /// @param tick The current tick /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The current in-range pool liquidity /// @param cardinality The number of populated elements in the oracle array /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo` /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo` function observeSingle( Observation[65535] storage self, uint32 time, uint32 secondsAgo, int24 tick, uint16 index, uint128 liquidity, uint16 cardinality ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) { if (secondsAgo == 0) { Observation memory last = self[index]; if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity); return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128); } uint32 target = time - secondsAgo; (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality); if (target == beforeOrAt.blockTimestamp) { // we're at the left boundary return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128); } else if (target == atOrAfter.blockTimestamp) { // we're at the right boundary return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128); } else { // we're in the middle uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp; uint32 targetDelta = target - beforeOrAt.blockTimestamp; return ( beforeOrAt.tickCumulative + ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) * targetDelta, beforeOrAt.secondsPerLiquidityCumulativeX128 + uint160( (uint256( atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128 ) * targetDelta) / observationTimeDelta ) ); } } /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos` /// @dev Reverts if `secondsAgos` > oldest observation /// @param self The stored oracle array /// @param time The current block.timestamp /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation /// @param tick The current tick /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The current in-range pool liquidity /// @param cardinality The number of populated elements in the oracle array /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo` /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo` function observe( Observation[65535] storage self, uint32 time, uint32[] memory secondsAgos, int24 tick, uint16 index, uint128 liquidity, uint16 cardinality ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) { require(cardinality > 0, 'I'); tickCumulatives = new int56[](secondsAgos.length); secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length); for (uint256 i = 0; i < secondsAgos.length; i++) { (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle( self, time, secondsAgos[i], tick, index, liquidity, cardinality ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then 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(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } 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 // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use 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. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // 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 precoditions 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 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '../interfaces/IERC20Minimal.sol'; /// @title TransferHelper /// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false library TransferHelper { /// @notice Transfers tokens from msg.sender to a recipient /// @dev Calls transfer on token contract, errors with TF if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { if (y < 0) { require((z = x - uint128(-y)) < x, 'LS'); } else { require((z = x + uint128(y)) >= x, 'LA'); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './FullMath.sol'; import './UnsafeMath.sol'; import './FixedPoint96.sol'; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './FullMath.sol'; import './SqrtPriceMath.sol'; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive /// @param sqrtRatioCurrentX96 The current sqrt price of the pool /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtRatioCurrentX96, uint160 sqrtRatioTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns ( uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount ) { bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96; bool exactIn = amountRemaining >= 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false); if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, uint256(-amountRemaining), zeroForOne ); } bool max = sqrtRatioTargetX96 == sqrtRatioNextX96; // get the input/output amounts if (zeroForOne) { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false); } else { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false); } // cap the output amount to not exceed the remaining output amount if (!exactIn && amountOut > uint256(-amountRemaining)) { amountOut = uint256(-amountRemaining); } if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) { // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(amountRemaining) - amountIn; } else { feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title An interface for a contract that is capable of deploying Uniswap V3 Pools /// @notice A contract that constructs a pool must implement this to pass arguments to the pool /// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash /// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain interface IUniswapV3PoolDeployer { /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation. /// @dev Called by the pool constructor to fetch the parameters of the pool /// Returns factory The factory address /// Returns token0 The first token of the pool by address sort order /// Returns token1 The second token of the pool by address sort order /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// Returns tickSpacing The minimum number of ticks between initialized ticks function parameters() external view returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#flash /// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface interface IUniswapV3FlashCallback { /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash. /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param fee0 The fee amount in token0 due to the pool by the end of the flash /// @param fee1 The fee amount in token1 due to the pool by the end of the flash /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
File 6 of 7: AugustusFeeVault
// SPDX-License-Identifier: MIT pragma solidity 0.8.22; // Contracts import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; // Interfaces import { IAugustusFeeVault } from "../interfaces/IAugustusFeeVault.sol"; import { IERC20 } from "@openzeppelin/token/ERC20/IERC20.sol"; // Libraries import { ERC20Utils } from "../libraries/ERC20Utils.sol"; /// @title Augstus Fee Vault /// @notice Allows partners to collect fees stored in the vault, and allows augustus contracts to register fees contract AugustusFeeVault is IAugustusFeeVault, Ownable, Pausable { /*////////////////////////////////////////////////////////////// LIBRARIES //////////////////////////////////////////////////////////////*/ using ERC20Utils for IERC20; /*////////////////////////////////////////////////////////////// VARIABLES //////////////////////////////////////////////////////////////*/ /// @dev A mapping of augustus contract addresses to their approval status mapping(address augustus => bool approved) public augustusContracts; // @dev Mapping of fee tokens to stored fee amounts mapping(address account => mapping(IERC20 token => uint256 amount)) public fees; // @dev Mapping of fee tokens to allocated fee amounts mapping(IERC20 token => uint256 amount) public allocatedFees; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(address[] memory _augustusContracts, address owner) Ownable(owner) { // Set augustus verifier contracts for (uint256 i = 0; i < _augustusContracts.length; i++) { augustusContracts[_augustusContracts[i]] = true; emit AugustusApprovalSet(_augustusContracts[i], true); } } /*////////////////////////////////////////////////////////////// MODIFIERS //////////////////////////////////////////////////////////////*/ /// @dev Modifier to check if the caller is an approved augustus contract modifier onlyApprovedAugustus() { if (!augustusContracts[msg.sender]) { revert UnauthorizedCaller(); } _; } /// @dev Verifies that the withdraw amount is not zero modifier validAmount(uint256 amount) { // Check if amount is zero if (amount == 0) { revert InvalidWithdrawAmount(); } _; } /*////////////////////////////////////////////////////////////// PUBLIC //////////////////////////////////////////////////////////////*/ /// @inheritdoc IAugustusFeeVault function withdrawSomeERC20( IERC20 token, uint256 amount, address recipient ) public validAmount(amount) whenNotPaused returns (bool success) { /// Check recipient recipient = _checkRecipient(recipient); // Update fees mapping _updateFees(token, msg.sender, amount); // Transfer tokens to recipient token.safeTransfer(recipient, amount); // Return success return true; } /// @inheritdoc IAugustusFeeVault function getUnallocatedFees(IERC20 token) public view returns (uint256 unallocatedFees) { // Get the allocated fees for the given token uint256 allocatedFee = allocatedFees[token]; // Get the balance of the given token uint256 balance = token.getBalance(address(this)); // If the balance is bigger than the allocated fee, then the unallocated fees should // be equal to the balance minus the allocated fee if (balance > allocatedFee) { // Set the unallocated fees to the balance minus the allocated fee unallocatedFees = balance - allocatedFee; } } /*/////////////////////////////////////////////////////////////// EXTERNAL //////////////////////////////////////////////////////////////*/ /// @inheritdoc IAugustusFeeVault function batchWithdrawSomeERC20( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external whenNotPaused returns (bool success) { // Check if the length of the tokens and amounts arrays are the same if (tokens.length != amounts.length) { revert InvalidParameterLength(); } // Loop through the tokens and amounts arrays for (uint256 i; i < tokens.length; ++i) { // Collect fees for the given token if (!withdrawSomeERC20(tokens[i], amounts[i], recipient)) { // Revert if collect fails revert BatchCollectFailed(); } } // Return success return true; } /// @inheritdoc IAugustusFeeVault function withdrawAllERC20(IERC20 token, address recipient) public whenNotPaused returns (bool success) { // Check recipient recipient = _checkRecipient(recipient); // Get the total fees for msg.sender in the given token uint256 totalBalance = fees[msg.sender][token]; // Make sure the amount is not zero if (totalBalance == 0) { revert InvalidWithdrawAmount(); } // Update fees mapping _updateFees(token, msg.sender, totalBalance); // Transfer tokens to recipient token.safeTransfer(recipient, totalBalance); // Return success return true; } /// @inheritdoc IAugustusFeeVault function batchWithdrawAllERC20( IERC20[] calldata tokens, address recipient ) external whenNotPaused returns (bool success) { // Loop through the tokens array for (uint256 i; i < tokens.length; ++i) { // Collect all fees for the given token if (!withdrawAllERC20(tokens[i], recipient)) { // Revert if withdrawAllERC20 fails revert BatchCollectFailed(); } } // Return success return true; } /// @inheritdoc IAugustusFeeVault function registerFees(FeeRegistration memory feeData) external onlyApprovedAugustus { // Get the addresses, tokens, and feeAmounts from the feeData struct address[] memory addresses = feeData.addresses; IERC20 token = feeData.token; uint256[] memory feeAmounts = feeData.fees; // Make sure the length of the addresses and feeAmounts arrays are the same if (addresses.length != feeAmounts.length) { revert InvalidParameterLength(); } // Loop through the addresses and fees arrays for (uint256 i; i < addresses.length; ++i) { // Register the fees for the given address and token if the fee and address are not zero if (feeAmounts[i] != 0 && addresses[i] != address(0)) { _registerFee(addresses[i], token, feeAmounts[i]); } } } /// @inheritdoc IAugustusFeeVault function setAugustusApproval(address augustus, bool approved) external onlyOwner { // Set the approval status for the given augustus contract augustusContracts[augustus] = approved; // Emit an event emit AugustusApprovalSet(augustus, approved); } /// @inheritdoc IAugustusFeeVault function setContractPauseState(bool _isPaused) external onlyOwner { // Set the pause state if (_isPaused) { _pause(); } else { _unpause(); } } /// @inheritdoc IAugustusFeeVault function getBalance(IERC20 token, address partner) external view returns (uint256 feeBalance) { // Get the fees for the given token and partner return fees[partner][token]; } /// @inheritdoc IAugustusFeeVault function batchGetBalance( IERC20[] calldata tokens, address partner ) external view returns (uint256[] memory feeBalances) { // Initialize the feeBalances array feeBalances = new uint256[](tokens.length); // Loop through the tokens array for (uint256 i; i < tokens.length; ++i) { // Get the fees for the given token and partner feeBalances[i] = fees[partner][tokens[i]]; } } /*////////////////////////////////////////////////////////////// PRIVATE //////////////////////////////////////////////////////////////*/ /// @notice Register fees for a given account and token /// @param account The account to register the fees for /// @param token The token to register the fees for /// @param fee The amount of fees to register function _registerFee(address account, IERC20 token, uint256 fee) private { // Get the unallocated fees for the given token uint256 unallocatedFees = getUnallocatedFees(token); // Make sure the fee is not bigger than the unallocated fees if (fee > unallocatedFees) { // If it is, set the fee to the unallocated fees fee = unallocatedFees; } // Update the fees mapping fees[account][token] += fee; // Update the allocated fees mapping allocatedFees[token] += fee; } /// @notice Update fees and allocatedFees for a given token and claimer /// @param token The token to update the fees for /// @param claimer The address to withdraw the fees for /// @param withdrawAmount The amount of fees to withdraw function _updateFees(IERC20 token, address claimer, uint256 withdrawAmount) private { // get the fees for the claimer uint256 feesForClaimer = fees[claimer][token]; // revert if withdraw amount is bigger than the fees for the claimer if (withdrawAmount > feesForClaimer) { revert InvalidWithdrawAmount(); } // update the allocated fees allocatedFees[token] -= withdrawAmount; // update the fees for the claimer fees[claimer][token] -= withdrawAmount; } /// @notice Check if recipient is zero address and set it to msg sender if it is, otherwise return recipient /// @param recipient The recipient address /// @return recipient The updated recipient address function _checkRecipient(address recipient) private view returns (address) { // Allow arbitrary recipient unless it is zero address if (recipient == address(0)) { recipient = msg.sender; } // Return recipient return recipient; } /*////////////////////////////////////////////////////////////// RECEIVE //////////////////////////////////////////////////////////////*/ /// @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 { 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 // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ 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 { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ 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 { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { bool private _paused; /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); /** * @dev The operation failed because the contract is paused. */ error EnforcedPause(); /** * @dev The operation failed because the contract is not paused. */ error ExpectedPause(); /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { if (paused()) { revert EnforcedPause(); } } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { if (!paused()) { revert ExpectedPause(); } } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // 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 // 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 { 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 // OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
File 7 of 7: SwapRouter
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/libraries/SafeCast.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './interfaces/ISwapRouter.sol'; import './base/PeripheryImmutableState.sol'; import './base/PeripheryValidation.sol'; import './base/PeripheryPaymentsWithFee.sol'; import './base/Multicall.sol'; import './base/SelfPermit.sol'; import './libraries/Path.sol'; import './libraries/PoolAddress.sol'; import './libraries/CallbackValidation.sol'; import './interfaces/external/IWETH9.sol'; /// @title Uniswap V3 Swap Router /// @notice Router for stateless execution of swaps against Uniswap V3 contract SwapRouter is ISwapRouter, PeripheryImmutableState, PeripheryValidation, PeripheryPaymentsWithFee, Multicall, SelfPermit { using Path for bytes; using SafeCast for uint256; /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap /// can never actually be this value uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max; /// @dev Transient storage variable used for returning the computed amount in for an exact output swap. uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED; constructor(address _factory, address _WETH9) PeripheryImmutableState(_factory, _WETH9) {} /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist. function getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee))); } struct SwapCallbackData { bytes path; address payer; } /// @inheritdoc IUniswapV3SwapCallback function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta)); if (isExactInput) { pay(tokenIn, data.payer, msg.sender, amountToPay); } else { // either initiate the next swap or pay if (data.path.hasMultiplePools()) { data.path = data.path.skipToken(); exactOutputInternal(amountToPay, msg.sender, 0, data); } else { amountInCached = amountToPay; tokenIn = tokenOut; // swap in/out because exact output swaps are reversed pay(tokenIn, data.payer, msg.sender, amountToPay); } } } /// @dev Performs a single exact input swap function exactInputInternal( uint256 amountIn, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountOut) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0, int256 amount1) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, amountIn.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); return uint256(-(zeroForOne ? amount1 : amount0)); } /// @inheritdoc ISwapRouter function exactInputSingle(ExactInputSingleParams calldata params) external payable override checkDeadline(params.deadline) returns (uint256 amountOut) { amountOut = exactInputInternal( params.amountIn, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender}) ); require(amountOut >= params.amountOutMinimum, 'Too little received'); } /// @inheritdoc ISwapRouter function exactInput(ExactInputParams memory params) external payable override checkDeadline(params.deadline) returns (uint256 amountOut) { address payer = msg.sender; // msg.sender pays for the first hop while (true) { bool hasMultiplePools = params.path.hasMultiplePools(); // the outputs of prior swaps become the inputs to subsequent ones params.amountIn = exactInputInternal( params.amountIn, hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies 0, SwapCallbackData({ path: params.path.getFirstPool(), // only the first pool in the path is necessary payer: payer }) ); // decide whether to continue or terminate if (hasMultiplePools) { payer = address(this); // at this point, the caller has paid params.path = params.path.skipToken(); } else { amountOut = params.amountIn; break; } } require(amountOut >= params.amountOutMinimum, 'Too little received'); } /// @dev Performs a single exact output swap function exactOutputInternal( uint256 amountOut, address recipient, uint160 sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256 amountIn) { // allow swapping to the router address with address 0 if (recipient == address(0)) recipient = address(this); (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool(); bool zeroForOne = tokenIn < tokenOut; (int256 amount0Delta, int256 amount1Delta) = getPool(tokenIn, tokenOut, fee).swap( recipient, zeroForOne, -amountOut.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encode(data) ); uint256 amountOutReceived; (amountIn, amountOutReceived) = zeroForOne ? (uint256(amount0Delta), uint256(-amount1Delta)) : (uint256(amount1Delta), uint256(-amount0Delta)); // it's technically possible to not receive the full output amount, // so if no price limit has been specified, require this possibility away if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut); } /// @inheritdoc ISwapRouter function exactOutputSingle(ExactOutputSingleParams calldata params) external payable override checkDeadline(params.deadline) returns (uint256 amountIn) { // avoid an SLOAD by using the swap return data amountIn = exactOutputInternal( params.amountOut, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender}) ); require(amountIn <= params.amountInMaximum, 'Too much requested'); // has to be reset even though we don't use it in the single hop case amountInCached = DEFAULT_AMOUNT_IN_CACHED; } /// @inheritdoc ISwapRouter function exactOutput(ExactOutputParams calldata params) external payable override checkDeadline(params.deadline) returns (uint256 amountIn) { // it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output // swap, which happens first, and subsequent swaps are paid for within nested callback frames exactOutputInternal( params.amountOut, params.recipient, 0, SwapCallbackData({path: params.path, payer: msg.sender}) ); amountIn = amountInCached; require(amountIn <= params.amountInMaximum, 'Too much requested'); amountInCached = DEFAULT_AMOUNT_IN_CACHED; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '../interfaces/IPeripheryImmutableState.sol'; /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract PeripheryImmutableState is IPeripheryImmutableState { /// @inheritdoc IPeripheryImmutableState address public immutable override factory; /// @inheritdoc IPeripheryImmutableState address public immutable override WETH9; constructor(address _factory, address _WETH9) { factory = _factory; WETH9 = _WETH9; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import './BlockTimestamp.sol'; abstract contract PeripheryValidation is BlockTimestamp { modifier checkDeadline(uint256 deadline) { require(_blockTimestamp() <= deadline, 'Transaction too old'); _; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import './PeripheryPayments.sol'; import '../interfaces/IPeripheryPaymentsWithFee.sol'; import '../interfaces/external/IWETH9.sol'; import '../libraries/TransferHelper.sol'; abstract contract PeripheryPaymentsWithFee is PeripheryPayments, IPeripheryPaymentsWithFee { using LowGasSafeMath for uint256; /// @inheritdoc IPeripheryPaymentsWithFee function unwrapWETH9WithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this)); require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9'); if (balanceWETH9 > 0) { IWETH9(WETH9).withdraw(balanceWETH9); uint256 feeAmount = balanceWETH9.mul(feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount); TransferHelper.safeTransferETH(recipient, balanceWETH9 - feeAmount); } } /// @inheritdoc IPeripheryPaymentsWithFee function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceToken = IERC20(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { uint256 feeAmount = balanceToken.mul(feeBips) / 10_000; if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount); TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/drafts/IERC20Permit.sol'; import '../interfaces/ISelfPermit.sol'; import '../interfaces/external/IERC20PermitAllowed.sol'; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route /// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function /// that requires an approval in a single transaction. abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './PoolAddress.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; /// @title Function for getting block timestamp /// @dev Base contract that is overridden for tests abstract contract BlockTimestamp { /// @dev Method that exists purely to be overridden for tests /// @return The current block timestamp function _blockTimestamp() internal view virtual returns (uint256) { return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '../interfaces/IPeripheryPayments.sol'; import '../interfaces/external/IWETH9.sol'; import '../libraries/TransferHelper.sol'; import './PeripheryImmutableState.sol'; abstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState { receive() external payable { require(msg.sender == WETH9, 'Not WETH9'); } /// @inheritdoc IPeripheryPayments function unwrapWETH9(uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this)); require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9'); if (balanceWETH9 > 0) { IWETH9(WETH9).withdraw(balanceWETH9); TransferHelper.safeTransferETH(recipient, balanceWETH9); } } /// @inheritdoc IPeripheryPayments function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable override { uint256 balanceToken = IERC20(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { TransferHelper.safeTransfer(token, recipient, balanceToken); } } /// @inheritdoc IPeripheryPayments function refundETH() external payable override { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == WETH9 && address(this).balance >= value) { // pay with WETH9 IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay IWETH9(WETH9).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import './IPeripheryPayments.sol'; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPaymentsWithFee is IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between /// 0 (exclusive), and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. function unwrapWETH9WithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; /// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between /// 0 (exclusive) and 1 (inclusive) going to feeRecipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Multicall interface /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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. */ 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]. */ 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: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route interface ISelfPermit { /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Interface for permit /// @notice Interface used by DAI/CHAI for permit interface IERC20PermitAllowed { /// @notice Approve the spender to spend some tokens via the holder signature /// @dev This is the permit interface used by DAI and CHAI /// @param holder The address of the token holder, the token owner /// @param spender The address of the token spender /// @param nonce The holder's nonce, increases at each call to permit /// @param expiry The timestamp at which the permit is no longer valid /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0 /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } }