From f1c075cc5f4eac50ae3a683d381cf778fcd3aef7 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 15:27:08 +0400 Subject: [PATCH 01/19] Remove baseline submodule from git --- .gitmodules | 6 +++--- lib/baseline-v2 | 1 - remappings.txt | 1 - script/install.sh | 12 ++++++------ 4 files changed, 9 insertions(+), 11 deletions(-) delete mode 160000 lib/baseline-v2 diff --git a/.gitmodules b/.gitmodules index 59285366..6b2efaaf 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "lib/baseline-v2"] - path = lib/baseline-v2 - url = git@github.com:0xBaseline/baseline-v2.git +# [submodule "lib/baseline-v2"] +# path = lib/baseline-v2 +# url = git@github.com:0xBaseline/baseline-v2.git diff --git a/lib/baseline-v2 b/lib/baseline-v2 deleted file mode 160000 index 60bed78b..00000000 --- a/lib/baseline-v2 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 60bed78b7bee28016321ddd8c590df6c61bae6e9 diff --git a/remappings.txt b/remappings.txt index 15d8ebcc..a6fe0d75 100644 --- a/remappings.txt +++ b/remappings.txt @@ -16,4 +16,3 @@ @openzeppelin/contracts=dependencies/@openzeppelin-contracts-4.9.2 @openzeppelin/contracts-upgradeable=dependencies/@openzeppelin-contracts-upgradeable-4.9.2 @solady-0.0.124=dependencies/solady-0.0.124/src -@baseline=lib/baseline-v2/src \ No newline at end of file diff --git a/script/install.sh b/script/install.sh index df5ba221..23b2383b 100755 --- a/script/install.sh +++ b/script/install.sh @@ -20,13 +20,13 @@ echo " Done" echo "" echo "*** Restoring submodule commits" -echo "" -echo "baseline" -cd lib/baseline-v2/ && git checkout 8950018baec27d6497fba409cb361a596535447d && cd ../.. +# echo "" +# echo "baseline" +# cd lib/baseline-v2/ && git checkout 8950018baec27d6497fba409cb361a596535447d && cd ../.. -echo "" -echo "*** Applying patch to Baseline submodule" -patch -d lib/baseline-v2/ -p1 < script/patch/baseline.patch +# echo "" +# echo "*** Applying patch to Baseline submodule" +# patch -d lib/baseline-v2/ -p1 < script/patch/baseline.patch echo "" echo "*** Installing soldeer dependencies" From de1b0f0ecdae507a13e9994181e572ef977b40ad Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 15:50:21 +0400 Subject: [PATCH 02/19] Comment-out references to Baseline --- script/deploy/Deploy.s.sol | 632 +++--- script/salts/dtl-baseline/BaselineSalts.s.sol | 3 +- script/salts/test/TestSalts.s.sol | 115 +- .../BaselineV2/BALwithAllocatedAllowlist.sol | 352 ++-- .../liquidity/BaselineV2/BALwithAllowlist.sol | 298 +-- .../BaselineV2/BALwithCappedAllowlist.sol | 190 +- .../BaselineV2/BALwithTokenAllowlist.sol | 234 +-- .../BaselineV2/BaselineAxisLaunch.sol | 1864 ++++++++--------- .../BaselineAllocatedAllowlistTest.sol | 3 +- .../BaselineV2/AllocatedAllowlist/onBid.t.sol | 3 +- .../AllocatedAllowlist/onCreate.t.sol | 3 +- .../AllocatedAllowlist/setMerkleRoot.t.sol | 3 +- .../Allowlist/BaselineAllowlistTest.sol | 3 +- .../BaselineV2/Allowlist/onBid.t.sol | 3 +- .../BaselineV2/Allowlist/onCreate.t.sol | 3 +- .../BaselineV2/Allowlist/setMerkleRoot.t.sol | 3 +- .../liquidity/BaselineV2/BPOOLMinter.sol | 3 +- .../BaselineV2/BaselineAxisLaunchTest.sol | 3 +- .../BaselineCappedAllowlistTest.sol | 3 +- .../BaselineV2/CappedAllowlist/onBid.t.sol | 3 +- .../BaselineV2/CappedAllowlist/onCreate.t.sol | 3 +- .../CappedAllowlist/setMerkleRoot.t.sol | 3 +- .../liquidity/BaselineV2/MockBlast.sol | 3 +- .../BaselineTokenAllowlistTest.sol | 3 +- .../BaselineV2/TokenAllowlist/onBid.t.sol | 3 +- .../BaselineV2/TokenAllowlist/onCreate.t.sol | 3 +- .../liquidity/BaselineV2/onCancel.t.sol | 3 +- .../liquidity/BaselineV2/onCreate.t.sol | 1393 +----------- .../liquidity/BaselineV2/onCurate.t.sol | 3 +- .../liquidity/BaselineV2/onSettle.t.sol | 3 +- .../liquidity/BaselineV2/slide.t.sol | 3 +- .../liquidity/BaselineV2/sweep.t.sol | 3 +- test/invariant/AxisInvariant.sol | 20 +- test/invariant/Setup.sol | 364 ++-- .../invariant/handlers/BaselineDTLHandler.sol | 21 +- .../handlers/BaselinePoolHandler.sol | 3 +- test/invariant/helpers/BeforeAfter.sol | 20 +- test/invariant/helpers/GuardianTester.sol | 31 +- test/invariant/modules/BPOOLMinter.sol | 3 +- test/invariant/modules/CREDTMinter.sol | 3 +- 40 files changed, 2134 insertions(+), 3481 deletions(-) diff --git a/script/deploy/Deploy.s.sol b/script/deploy/Deploy.s.sol index 3daf8570..ea5b4ac8 100644 --- a/script/deploy/Deploy.s.sol +++ b/script/deploy/Deploy.s.sol @@ -26,20 +26,20 @@ import {CappedMerkleAllowlist} from "../../src/callbacks/allowlists/CappedMerkle import {MerkleAllowlist} from "../../src/callbacks/allowlists/MerkleAllowlist.sol"; import {TokenAllowlist} from "../../src/callbacks/allowlists/TokenAllowlist.sol"; import {AllocatedMerkleAllowlist} from "../../src/callbacks/allowlists/AllocatedMerkleAllowlist.sol"; -import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {BALwithAllowlist} from "../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; -import {BALwithAllocatedAllowlist} from - "../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; -import {BALwithCappedAllowlist} from - "../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -import {BALwithTokenAllowlist} from - "../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; +// import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; +// import {BALwithAllowlist} from "../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; +// import {BALwithAllocatedAllowlist} from +// "../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; +// import {BALwithCappedAllowlist} from +// "../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; +// import {BALwithTokenAllowlist} from +// "../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; // Baseline -import { - Kernel as BaselineKernel, - Actions as BaselineKernelActions -} from "../../src/callbacks/liquidity/BaselineV2/lib/Kernel.sol"; +// import { +// Kernel as BaselineKernel, +// Actions as BaselineKernelActions +// } from "../../src/callbacks/liquidity/BaselineV2/lib/Kernel.sol"; /// @notice Declarative deployment script that reads a deployment sequence (with constructor args) /// and a configured environment file to deploy and install contracts in the Axis protocol. @@ -787,310 +787,310 @@ contract Deploy is Script, WithDeploySequence, WithSalts { return (address(cbBatchAllocatedMerkleAllowlist), _PREFIX_CALLBACKS, deploymentKey); } - function deployBatchBaselineAxisLaunch( - string memory sequenceName_ - ) public returns (address, string memory, string memory) { - console2.log(""); - console2.log("Deploying BaselineAxisLaunch (Batch)"); - - // Get configuration variables - address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - console2.log(" baselineKernel:", baselineKernel); - address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - console2.log(" baselineOwner:", baselineOwner); - address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - console2.log(" reserveToken:", reserveToken); - string memory deploymentKey = _getDeploymentKey(sequenceName_); - console2.log(" deploymentKey:", deploymentKey); - - // Validate arguments - require(baselineKernel != address(0), "baselineKernel not set"); - require(baselineOwner != address(0), "baselineOwner not set"); - require(reserveToken != address(0), "reserveToken not set"); - - // Get the salt - // This supports an arbitrary salt key, which can be set in the deployment sequence - // This is required as each callback is single-use - bytes32 salt_ = _getSalt( - deploymentKey, - type(BaselineAxisLaunch).creationCode, - abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - ); - - // Revert if the salt is not set - require(salt_ != bytes32(0), "Salt not set"); - - // Deploy the module - console2.log(" salt:", vm.toString(salt_)); - - vm.broadcast(); - BaselineAxisLaunch batchCallback = new BaselineAxisLaunch{salt: salt_}( - batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - ); - console2.log(""); - console2.log(" deployed at:", address(batchCallback)); - - // If the deployer is the executor, - // install the module as a policy in the Baseline kernel - BaselineKernel kernel = BaselineKernel(baselineKernel); - if (kernel.executor() == msg.sender) { - vm.broadcast(); - BaselineKernel(baselineKernel).executeAction( - BaselineKernelActions.ActivatePolicy, address(batchCallback) - ); - - console2.log(" Policy activated in Baseline Kernel"); - } else { - console2.log(" Policy activation skipped"); - } - - return (address(batchCallback), _PREFIX_CALLBACKS, deploymentKey); - } - - function deployBatchBaselineAllocatedAllowlist( - string memory sequenceName_ - ) public returns (address, string memory, string memory) { - console2.log(""); - console2.log("Deploying BaselineAllocatedAllowlist (Batch)"); - - // Get configuration variables - address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - console2.log(" baselineKernel:", baselineKernel); - address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - console2.log(" baselineOwner:", baselineOwner); - address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - console2.log(" reserveToken:", reserveToken); - string memory deploymentKey = _getDeploymentKey(sequenceName_); - console2.log(" deploymentKey:", deploymentKey); - - // Validate arguments - require(baselineKernel != address(0), "baselineKernel not set"); - require(baselineOwner != address(0), "baselineOwner not set"); - require(reserveToken != address(0), "reserveToken not set"); - - // Get the salt - // This supports an arbitrary salt key, which can be set in the deployment sequence - // This is required as each callback is single-use - bytes32 salt_ = _getSalt( - deploymentKey, - type(BALwithAllocatedAllowlist).creationCode, - abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - ); - - // Revert if the salt is not set - require(salt_ != bytes32(0), "Salt not set"); - - // Deploy the module - console2.log(" salt:", vm.toString(salt_)); - - vm.broadcast(); - BALwithAllocatedAllowlist batchAllowlist = new BALwithAllocatedAllowlist{salt: salt_}( - batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - ); - console2.log(""); - console2.log(" deployed at:", address(batchAllowlist)); - - // If the deployer is the executor, - // install the module as a policy in the Baseline kernel - BaselineKernel kernel = BaselineKernel(baselineKernel); - if (kernel.executor() == msg.sender) { - vm.broadcast(); - BaselineKernel(baselineKernel).executeAction( - BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - ); - - console2.log(" Policy activated in Baseline Kernel"); - } else { - console2.log(" Policy activation skipped"); - } - - return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - } - - function deployBatchBaselineAllowlist( - string memory sequenceName_ - ) public returns (address, string memory, string memory) { - console2.log(""); - console2.log("Deploying BaselineAllowlist (Batch)"); - - // Get configuration variables - address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - console2.log(" baselineKernel:", baselineKernel); - address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - console2.log(" baselineOwner:", baselineOwner); - address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - console2.log(" reserveToken:", reserveToken); - string memory deploymentKey = _getDeploymentKey(sequenceName_); - console2.log(" deploymentKey:", deploymentKey); - - // Validate arguments - require(baselineKernel != address(0), "baselineKernel not set"); - require(baselineOwner != address(0), "baselineOwner not set"); - require(reserveToken != address(0), "reserveToken not set"); - - // Get the salt - // This supports an arbitrary salt key, which can be set in the deployment sequence - // This is required as each callback is single-use - bytes32 salt_ = _getSalt( - deploymentKey, - type(BALwithAllowlist).creationCode, - abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - ); - - // Revert if the salt is not set - require(salt_ != bytes32(0), "Salt not set"); - - // Deploy the module - console2.log(" salt:", vm.toString(salt_)); - - vm.broadcast(); - BALwithAllowlist batchAllowlist = new BALwithAllowlist{salt: salt_}( - batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - ); - console2.log(""); - console2.log(" deployed at:", address(batchAllowlist)); - - // If the deployer is the executor, - // install the module as a policy in the Baseline kernel - BaselineKernel kernel = BaselineKernel(baselineKernel); - if (kernel.executor() == msg.sender) { - vm.broadcast(); - BaselineKernel(baselineKernel).executeAction( - BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - ); - - console2.log(" Policy activated in Baseline Kernel"); - } else { - console2.log(" Policy activation skipped"); - } - - return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - } - - function deployBatchBaselineCappedAllowlist( - string memory sequenceName_ - ) public returns (address, string memory, string memory) { - console2.log(""); - console2.log("Deploying BaselineCappedAllowlist (Batch)"); - - // Get configuration variables - address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - console2.log(" baselineKernel:", baselineKernel); - address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - console2.log(" baselineOwner:", baselineOwner); - address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - console2.log(" reserveToken:", reserveToken); - string memory deploymentKey = _getDeploymentKey(sequenceName_); - console2.log(" deploymentKey:", deploymentKey); - - // Validate arguments - require(baselineKernel != address(0), "baselineKernel not set"); - require(baselineOwner != address(0), "baselineOwner not set"); - require(reserveToken != address(0), "reserveToken not set"); - - // Get the salt - // This supports an arbitrary salt key, which can be set in the deployment sequence - // This is required as each callback is single-use - bytes32 salt_ = _getSalt( - deploymentKey, - type(BALwithCappedAllowlist).creationCode, - abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - ); - - // Revert if the salt is not set - require(salt_ != bytes32(0), "Salt not set"); - - // Deploy the module - console2.log(" salt:", vm.toString(salt_)); - - vm.broadcast(); - BALwithCappedAllowlist batchAllowlist = new BALwithCappedAllowlist{salt: salt_}( - batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - ); - console2.log(""); - console2.log(" deployed at:", address(batchAllowlist)); - - // If the deployer is the executor, - // install the module as a policy in the Baseline kernel - BaselineKernel kernel = BaselineKernel(baselineKernel); - if (kernel.executor() == msg.sender) { - vm.broadcast(); - BaselineKernel(baselineKernel).executeAction( - BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - ); - - console2.log(" Policy activated in Baseline Kernel"); - } else { - console2.log(" Policy activation skipped"); - } - - return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - } - - function deployBatchBaselineTokenAllowlist( - string memory sequenceName_ - ) public returns (address, string memory, string memory) { - console2.log(""); - console2.log("Deploying BaselineTokenAllowlist (Batch)"); - - // Get configuration variables - address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - console2.log(" baselineKernel:", baselineKernel); - address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - console2.log(" baselineOwner:", baselineOwner); - address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - console2.log(" reserveToken:", reserveToken); - string memory deploymentKey = _getDeploymentKey(sequenceName_); - console2.log(" deploymentKey:", deploymentKey); - - // Validate arguments - require(baselineKernel != address(0), "baselineKernel not set"); - require(baselineOwner != address(0), "baselineOwner not set"); - require(reserveToken != address(0), "reserveToken not set"); - - // Get the salt - // This supports an arbitrary salt key, which can be set in the deployment sequence - // This is required as each callback is single-use - bytes32 salt_ = _getSalt( - deploymentKey, - type(BALwithTokenAllowlist).creationCode, - abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - ); - - // Revert if the salt is not set - require(salt_ != bytes32(0), "Salt not set"); - - // Deploy the module - console2.log(" salt:", vm.toString(salt_)); - - vm.broadcast(); - BALwithTokenAllowlist batchAllowlist = new BALwithTokenAllowlist{salt: salt_}( - batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - ); - console2.log(""); - console2.log(" deployed at:", address(batchAllowlist)); - - // If the deployer is the executor, - // install the module as a policy in the Baseline kernel - BaselineKernel kernel = BaselineKernel(baselineKernel); - if (kernel.executor() == msg.sender) { - vm.broadcast(); - BaselineKernel(baselineKernel).executeAction( - BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - ); - - console2.log(" Policy activated in Baseline Kernel"); - } else { - console2.log(" Policy activation skipped"); - } - - return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - } + // function deployBatchBaselineAxisLaunch( + // string memory sequenceName_ + // ) public returns (address, string memory, string memory) { + // console2.log(""); + // console2.log("Deploying BaselineAxisLaunch (Batch)"); + + // // Get configuration variables + // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); + // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); + // console2.log(" baselineKernel:", baselineKernel); + // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); + // console2.log(" baselineOwner:", baselineOwner); + // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); + // console2.log(" reserveToken:", reserveToken); + // string memory deploymentKey = _getDeploymentKey(sequenceName_); + // console2.log(" deploymentKey:", deploymentKey); + + // // Validate arguments + // require(baselineKernel != address(0), "baselineKernel not set"); + // require(baselineOwner != address(0), "baselineOwner not set"); + // require(reserveToken != address(0), "reserveToken not set"); + + // // Get the salt + // // This supports an arbitrary salt key, which can be set in the deployment sequence + // // This is required as each callback is single-use + // bytes32 salt_ = _getSalt( + // deploymentKey, + // type(BaselineAxisLaunch).creationCode, + // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) + // ); + + // // Revert if the salt is not set + // require(salt_ != bytes32(0), "Salt not set"); + + // // Deploy the module + // console2.log(" salt:", vm.toString(salt_)); + + // vm.broadcast(); + // BaselineAxisLaunch batchCallback = new BaselineAxisLaunch{salt: salt_}( + // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner + // ); + // console2.log(""); + // console2.log(" deployed at:", address(batchCallback)); + + // // If the deployer is the executor, + // // install the module as a policy in the Baseline kernel + // BaselineKernel kernel = BaselineKernel(baselineKernel); + // if (kernel.executor() == msg.sender) { + // vm.broadcast(); + // BaselineKernel(baselineKernel).executeAction( + // BaselineKernelActions.ActivatePolicy, address(batchCallback) + // ); + + // console2.log(" Policy activated in Baseline Kernel"); + // } else { + // console2.log(" Policy activation skipped"); + // } + + // return (address(batchCallback), _PREFIX_CALLBACKS, deploymentKey); + // } + + // function deployBatchBaselineAllocatedAllowlist( + // string memory sequenceName_ + // ) public returns (address, string memory, string memory) { + // console2.log(""); + // console2.log("Deploying BaselineAllocatedAllowlist (Batch)"); + + // // Get configuration variables + // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); + // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); + // console2.log(" baselineKernel:", baselineKernel); + // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); + // console2.log(" baselineOwner:", baselineOwner); + // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); + // console2.log(" reserveToken:", reserveToken); + // string memory deploymentKey = _getDeploymentKey(sequenceName_); + // console2.log(" deploymentKey:", deploymentKey); + + // // Validate arguments + // require(baselineKernel != address(0), "baselineKernel not set"); + // require(baselineOwner != address(0), "baselineOwner not set"); + // require(reserveToken != address(0), "reserveToken not set"); + + // // Get the salt + // // This supports an arbitrary salt key, which can be set in the deployment sequence + // // This is required as each callback is single-use + // bytes32 salt_ = _getSalt( + // deploymentKey, + // type(BALwithAllocatedAllowlist).creationCode, + // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) + // ); + + // // Revert if the salt is not set + // require(salt_ != bytes32(0), "Salt not set"); + + // // Deploy the module + // console2.log(" salt:", vm.toString(salt_)); + + // vm.broadcast(); + // BALwithAllocatedAllowlist batchAllowlist = new BALwithAllocatedAllowlist{salt: salt_}( + // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner + // ); + // console2.log(""); + // console2.log(" deployed at:", address(batchAllowlist)); + + // // If the deployer is the executor, + // // install the module as a policy in the Baseline kernel + // BaselineKernel kernel = BaselineKernel(baselineKernel); + // if (kernel.executor() == msg.sender) { + // vm.broadcast(); + // BaselineKernel(baselineKernel).executeAction( + // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) + // ); + + // console2.log(" Policy activated in Baseline Kernel"); + // } else { + // console2.log(" Policy activation skipped"); + // } + + // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); + // } + + // function deployBatchBaselineAllowlist( + // string memory sequenceName_ + // ) public returns (address, string memory, string memory) { + // console2.log(""); + // console2.log("Deploying BaselineAllowlist (Batch)"); + + // // Get configuration variables + // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); + // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); + // console2.log(" baselineKernel:", baselineKernel); + // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); + // console2.log(" baselineOwner:", baselineOwner); + // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); + // console2.log(" reserveToken:", reserveToken); + // string memory deploymentKey = _getDeploymentKey(sequenceName_); + // console2.log(" deploymentKey:", deploymentKey); + + // // Validate arguments + // require(baselineKernel != address(0), "baselineKernel not set"); + // require(baselineOwner != address(0), "baselineOwner not set"); + // require(reserveToken != address(0), "reserveToken not set"); + + // // Get the salt + // // This supports an arbitrary salt key, which can be set in the deployment sequence + // // This is required as each callback is single-use + // bytes32 salt_ = _getSalt( + // deploymentKey, + // type(BALwithAllowlist).creationCode, + // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) + // ); + + // // Revert if the salt is not set + // require(salt_ != bytes32(0), "Salt not set"); + + // // Deploy the module + // console2.log(" salt:", vm.toString(salt_)); + + // vm.broadcast(); + // BALwithAllowlist batchAllowlist = new BALwithAllowlist{salt: salt_}( + // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner + // ); + // console2.log(""); + // console2.log(" deployed at:", address(batchAllowlist)); + + // // If the deployer is the executor, + // // install the module as a policy in the Baseline kernel + // BaselineKernel kernel = BaselineKernel(baselineKernel); + // if (kernel.executor() == msg.sender) { + // vm.broadcast(); + // BaselineKernel(baselineKernel).executeAction( + // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) + // ); + + // console2.log(" Policy activated in Baseline Kernel"); + // } else { + // console2.log(" Policy activation skipped"); + // } + + // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); + // } + + // function deployBatchBaselineCappedAllowlist( + // string memory sequenceName_ + // ) public returns (address, string memory, string memory) { + // console2.log(""); + // console2.log("Deploying BaselineCappedAllowlist (Batch)"); + + // // Get configuration variables + // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); + // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); + // console2.log(" baselineKernel:", baselineKernel); + // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); + // console2.log(" baselineOwner:", baselineOwner); + // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); + // console2.log(" reserveToken:", reserveToken); + // string memory deploymentKey = _getDeploymentKey(sequenceName_); + // console2.log(" deploymentKey:", deploymentKey); + + // // Validate arguments + // require(baselineKernel != address(0), "baselineKernel not set"); + // require(baselineOwner != address(0), "baselineOwner not set"); + // require(reserveToken != address(0), "reserveToken not set"); + + // // Get the salt + // // This supports an arbitrary salt key, which can be set in the deployment sequence + // // This is required as each callback is single-use + // bytes32 salt_ = _getSalt( + // deploymentKey, + // type(BALwithCappedAllowlist).creationCode, + // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) + // ); + + // // Revert if the salt is not set + // require(salt_ != bytes32(0), "Salt not set"); + + // // Deploy the module + // console2.log(" salt:", vm.toString(salt_)); + + // vm.broadcast(); + // BALwithCappedAllowlist batchAllowlist = new BALwithCappedAllowlist{salt: salt_}( + // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner + // ); + // console2.log(""); + // console2.log(" deployed at:", address(batchAllowlist)); + + // // If the deployer is the executor, + // // install the module as a policy in the Baseline kernel + // BaselineKernel kernel = BaselineKernel(baselineKernel); + // if (kernel.executor() == msg.sender) { + // vm.broadcast(); + // BaselineKernel(baselineKernel).executeAction( + // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) + // ); + + // console2.log(" Policy activated in Baseline Kernel"); + // } else { + // console2.log(" Policy activation skipped"); + // } + + // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); + // } + + // function deployBatchBaselineTokenAllowlist( + // string memory sequenceName_ + // ) public returns (address, string memory, string memory) { + // console2.log(""); + // console2.log("Deploying BaselineTokenAllowlist (Batch)"); + + // // Get configuration variables + // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); + // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); + // console2.log(" baselineKernel:", baselineKernel); + // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); + // console2.log(" baselineOwner:", baselineOwner); + // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); + // console2.log(" reserveToken:", reserveToken); + // string memory deploymentKey = _getDeploymentKey(sequenceName_); + // console2.log(" deploymentKey:", deploymentKey); + + // // Validate arguments + // require(baselineKernel != address(0), "baselineKernel not set"); + // require(baselineOwner != address(0), "baselineOwner not set"); + // require(reserveToken != address(0), "reserveToken not set"); + + // // Get the salt + // // This supports an arbitrary salt key, which can be set in the deployment sequence + // // This is required as each callback is single-use + // bytes32 salt_ = _getSalt( + // deploymentKey, + // type(BALwithTokenAllowlist).creationCode, + // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) + // ); + + // // Revert if the salt is not set + // require(salt_ != bytes32(0), "Salt not set"); + + // // Deploy the module + // console2.log(" salt:", vm.toString(salt_)); + + // vm.broadcast(); + // BALwithTokenAllowlist batchAllowlist = new BALwithTokenAllowlist{salt: salt_}( + // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner + // ); + // console2.log(""); + // console2.log(" deployed at:", address(batchAllowlist)); + + // // If the deployer is the executor, + // // install the module as a policy in the Baseline kernel + // BaselineKernel kernel = BaselineKernel(baselineKernel); + // if (kernel.executor() == msg.sender) { + // vm.broadcast(); + // BaselineKernel(baselineKernel).executeAction( + // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) + // ); + + // console2.log(" Policy activated in Baseline Kernel"); + // } else { + // console2.log(" Policy activation skipped"); + // } + + // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); + // } // ========== HELPER FUNCTIONS ========== // diff --git a/script/salts/dtl-baseline/BaselineSalts.s.sol b/script/salts/dtl-baseline/BaselineSalts.s.sol index ba1d0f74..ea72c095 100644 --- a/script/salts/dtl-baseline/BaselineSalts.s.sol +++ b/script/salts/dtl-baseline/BaselineSalts.s.sol @@ -1,6 +1,6 @@ /// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Scripting libraries import {Script, console2} from "@forge-std-1.9.1/Script.sol"; import {WithSalts} from "../WithSalts.s.sol"; @@ -169,3 +169,4 @@ contract BaselineSalts is Script, WithDeploySequence, WithSalts { _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); } } +*/ diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol index 37b0ee8b..5584c65d 100644 --- a/script/salts/test/TestSalts.s.sol +++ b/script/salts/test/TestSalts.s.sol @@ -25,15 +25,16 @@ import {AllocatedMerkleAllowlist} from import {TokenAllowlist} from "../../../src/callbacks/allowlists/TokenAllowlist.sol"; import {UniswapV2DirectToLiquidity} from "../../../src/callbacks/liquidity/UniswapV2DTL.sol"; import {UniswapV3DirectToLiquidity} from "../../../src/callbacks/liquidity/UniswapV3DTL.sol"; -import {BaselineAxisLaunch} from - "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {BALwithAllocatedAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; -import {BALwithAllowlist} from "../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; -import {BALwithCappedAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -import {BALwithTokenAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; + +// import {BaselineAxisLaunch} from +// "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; +// import {BALwithAllocatedAllowlist} from +// "../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; +// import {BALwithAllowlist} from "../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; +// import {BALwithCappedAllowlist} from +// "../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; +// import {BALwithTokenAllowlist} from +// "../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConstants { string internal constant _CAPPED_MERKLE_ALLOWLIST = "CappedMerkleAllowlist"; @@ -266,52 +267,52 @@ contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConst console2.log("Quote Token address: ", address(quoteToken)); } - function generateBaselineAxisLaunch() public { - // Get the salt - bytes memory callbackArgs = - abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - "BaselineAxisLaunch", type(BaselineAxisLaunch).creationCode, callbackArgs - ); - _setTestSalt(callbackBytecodePath, "EF", "BaselineAxisLaunch", callbackBytecodeHash); - } - - function generateBaselineAllocatedAllowlist() public { - // Get the salt - bytes memory callbackArgs = - abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - "BaselineAllocatedAllowlist", type(BALwithAllocatedAllowlist).creationCode, callbackArgs - ); - _setTestSalt(callbackBytecodePath, "EF", "BaselineAllocatedAllowlist", callbackBytecodeHash); - } - - function generateBaselineAllowlist() public { - // Get the salt - bytes memory callbackArgs = - abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = - _writeBytecode("BaselineAllowlist", type(BALwithAllowlist).creationCode, callbackArgs); - _setTestSalt(callbackBytecodePath, "EF", "BaselineAllowlist", callbackBytecodeHash); - } - - function generateBaselineCappedAllowlist() public { - // Get the salt - bytes memory callbackArgs = - abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - "BaselineCappedAllowlist", type(BALwithCappedAllowlist).creationCode, callbackArgs - ); - _setTestSalt(callbackBytecodePath, "EF", "BaselineCappedAllowlist", callbackBytecodeHash); - } - - function generateBaselineTokenAllowlist() public { - // Get the salt - bytes memory callbackArgs = - abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - "BaselineTokenAllowlist", type(BALwithTokenAllowlist).creationCode, callbackArgs - ); - _setTestSalt(callbackBytecodePath, "EF", "BaselineTokenAllowlist", callbackBytecodeHash); - } + // function generateBaselineAxisLaunch() public { + // // Get the salt + // bytes memory callbackArgs = + // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); + // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( + // "BaselineAxisLaunch", type(BaselineAxisLaunch).creationCode, callbackArgs + // ); + // _setTestSalt(callbackBytecodePath, "EF", "BaselineAxisLaunch", callbackBytecodeHash); + // } + + // function generateBaselineAllocatedAllowlist() public { + // // Get the salt + // bytes memory callbackArgs = + // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); + // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( + // "BaselineAllocatedAllowlist", type(BALwithAllocatedAllowlist).creationCode, callbackArgs + // ); + // _setTestSalt(callbackBytecodePath, "EF", "BaselineAllocatedAllowlist", callbackBytecodeHash); + // } + + // function generateBaselineAllowlist() public { + // // Get the salt + // bytes memory callbackArgs = + // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); + // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = + // _writeBytecode("BaselineAllowlist", type(BALwithAllowlist).creationCode, callbackArgs); + // _setTestSalt(callbackBytecodePath, "EF", "BaselineAllowlist", callbackBytecodeHash); + // } + + // function generateBaselineCappedAllowlist() public { + // // Get the salt + // bytes memory callbackArgs = + // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); + // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( + // "BaselineCappedAllowlist", type(BALwithCappedAllowlist).creationCode, callbackArgs + // ); + // _setTestSalt(callbackBytecodePath, "EF", "BaselineCappedAllowlist", callbackBytecodeHash); + // } + + // function generateBaselineTokenAllowlist() public { + // // Get the salt + // bytes memory callbackArgs = + // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); + // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( + // "BaselineTokenAllowlist", type(BALwithTokenAllowlist).creationCode, callbackArgs + // ); + // _setTestSalt(callbackBytecodePath, "EF", "BaselineTokenAllowlist", callbackBytecodeHash); + // } } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol index 9e652e6b..2894f86a 100644 --- a/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol +++ b/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol @@ -1,184 +1,184 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; +// import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; -import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; +// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; /// @notice Allocated allowlist version of the Baseline Axis Launch callback for batch auctions. /// @notice This version allows for each address in the Merkle tree to have a per-address amount of quote tokens they can spend. /// @dev The merkle tree is expected to have both an address and an amount of quote tokens they can spend in each leaf. -contract BALwithAllocatedAllowlist is BaselineAxisLaunch { - // ========== ERRORS ========== // - - /// @notice Error message when the bid amount exceeds the limit assigned to a buyer - error Callback_ExceedsLimit(); - - /// @notice Error message when the callback state does not support the action - error Callback_InvalidState(); - - // ========== EVENTS ========== // - - /// @notice Emitted when the merkle root is set - event MerkleRootSet(bytes32 merkleRoot); - - // ========== STATE VARIABLES ========== // - - /// @notice The root of the merkle tree that represents the allowlist - /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree - /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. - bytes32 public merkleRoot; - - /// @notice Tracks the cumulative amount spent by a buyer - mapping(address => uint256) public buyerSpent; - - // ========== CONSTRUCTOR ========== // - - // PERMISSIONS - // onCreate: true - // onCancel: true - // onCurate: true - // onPurchase: false - // onBid: true - // onSettle: true - // receiveQuoteTokens: true - // sendBaseTokens: true - // Contract prefix should be: 11101111 = 0xEF - - constructor( - address auctionHouse_, - address baselineKernel_, - address reserve_, - address owner_ - ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - - // ========== CALLBACK FUNCTIONS ========== // - - /// @inheritdoc BaselineAxisLaunch - /// @dev This function reverts if: - /// - `allowlistData_` is not of the correct length - /// - /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root - function __onCreate( - uint96, - address, - address, - address, - uint256, - bool, - bytes memory allowlistData_ - ) internal virtual override { - // Check that the parameters are of the correct length - if (allowlistData_.length != 32) { - revert Callback_InvalidParams(); - } - - // Decode the merkle root from the callback data - bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); - - // Set the merkle root and buyer limit - merkleRoot = merkleRootParams; - emit MerkleRootSet(merkleRoot); - } - - /// @inheritdoc BaselineAxisLaunch - /// - /// @param callbackData_ abi-encoded data: (bytes32[], uint256) representing the merkle proof and allocated amount - function _onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual override { - // Validate that the buyer is allowed to participate - uint256 allocatedAmount = _canParticipate(buyer_, callbackData_); - - // Validate that the buyer can buy the amount - _canBuy(buyer_, amount_, allocatedAmount); - - // Call any additional implementation-specific logic - __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); - } - - /// @notice Override this function to implement additional functionality for the `onBid` callback - /// - /// @param lotId_ The ID of the lot - /// @param bidId_ The ID of the bid - /// @param buyer_ The address of the buyer - /// @param amount_ The amount of quote tokens - /// @param callbackData_ The callback data - function __onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual {} - - // ========== INTERNAL FUNCTIONS ========== // - - /// @dev The buyer must provide the proof and their total allocated amount in the callback data for this to succeed. - function _canParticipate( - address buyer_, - bytes calldata callbackData_ - ) internal view returns (uint256) { - // Decode the merkle proof from the callback data - (bytes32[] memory proof, uint256 allocatedAmount) = - abi.decode(callbackData_, (bytes32[], uint256)); - - // Get the leaf for the buyer - bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_, allocatedAmount)))); - - // Validate the merkle proof - if (!MerkleProof.verify(proof, merkleRoot, leaf)) { - revert Callback_NotAuthorized(); - } - - // Return the allocated amount for the buyer - return allocatedAmount; - } - - function _canBuy(address buyer_, uint256 amount_, uint256 allocatedAmount_) internal { - // Check if the buyer has already spent their limit - if (buyerSpent[buyer_] + amount_ > allocatedAmount_) { - revert Callback_ExceedsLimit(); - } - - // Update the buyer spent amount - buyerSpent[buyer_] += amount_; - } - - // ========== ADMIN FUNCTIONS ========== // - - /// @notice Sets the merkle root for the allowlist - /// This function can be called by the owner to update the merkle root after `onCreate()`. - /// @dev This function performs the following: - /// - Performs validation - /// - Sets the merkle root - /// - Emits a MerkleRootSet event - /// - /// This function reverts if: - /// - The caller is not the owner - /// - The auction has not been registered - /// - The auction has been completed - /// - /// @param merkleRoot_ The new merkle root - function setMerkleRoot( - bytes32 merkleRoot_ - ) external onlyOwner { - // Revert if onCreate has not been called - if (lotId == type(uint96).max) { - revert Callback_InvalidState(); - } - - // Revert if the auction has been completed already - if (auctionComplete) { - revert Callback_InvalidState(); - } - - merkleRoot = merkleRoot_; - - emit MerkleRootSet(merkleRoot_); - } -} +// contract BALwithAllocatedAllowlist is BaselineAxisLaunch { +// // ========== ERRORS ========== // + +// /// @notice Error message when the bid amount exceeds the limit assigned to a buyer +// error Callback_ExceedsLimit(); + +// /// @notice Error message when the callback state does not support the action +// error Callback_InvalidState(); + +// // ========== EVENTS ========== // + +// /// @notice Emitted when the merkle root is set +// event MerkleRootSet(bytes32 merkleRoot); + +// // ========== STATE VARIABLES ========== // + +// /// @notice The root of the merkle tree that represents the allowlist +// /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree +// /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. +// bytes32 public merkleRoot; + +// /// @notice Tracks the cumulative amount spent by a buyer +// mapping(address => uint256) public buyerSpent; + +// // ========== CONSTRUCTOR ========== // + +// // PERMISSIONS +// // onCreate: true +// // onCancel: true +// // onCurate: true +// // onPurchase: false +// // onBid: true +// // onSettle: true +// // receiveQuoteTokens: true +// // sendBaseTokens: true +// // Contract prefix should be: 11101111 = 0xEF + +// constructor( +// address auctionHouse_, +// address baselineKernel_, +// address reserve_, +// address owner_ +// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} + +// // ========== CALLBACK FUNCTIONS ========== // + +// /// @inheritdoc BaselineAxisLaunch +// /// @dev This function reverts if: +// /// - `allowlistData_` is not of the correct length +// /// +// /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root +// function __onCreate( +// uint96, +// address, +// address, +// address, +// uint256, +// bool, +// bytes memory allowlistData_ +// ) internal virtual override { +// // Check that the parameters are of the correct length +// if (allowlistData_.length != 32) { +// revert Callback_InvalidParams(); +// } + +// // Decode the merkle root from the callback data +// bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); + +// // Set the merkle root and buyer limit +// merkleRoot = merkleRootParams; +// emit MerkleRootSet(merkleRoot); +// } + +// /// @inheritdoc BaselineAxisLaunch +// /// +// /// @param callbackData_ abi-encoded data: (bytes32[], uint256) representing the merkle proof and allocated amount +// function _onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual override { +// // Validate that the buyer is allowed to participate +// uint256 allocatedAmount = _canParticipate(buyer_, callbackData_); + +// // Validate that the buyer can buy the amount +// _canBuy(buyer_, amount_, allocatedAmount); + +// // Call any additional implementation-specific logic +// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); +// } + +// /// @notice Override this function to implement additional functionality for the `onBid` callback +// /// +// /// @param lotId_ The ID of the lot +// /// @param bidId_ The ID of the bid +// /// @param buyer_ The address of the buyer +// /// @param amount_ The amount of quote tokens +// /// @param callbackData_ The callback data +// function __onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual {} + +// // ========== INTERNAL FUNCTIONS ========== // + +// /// @dev The buyer must provide the proof and their total allocated amount in the callback data for this to succeed. +// function _canParticipate( +// address buyer_, +// bytes calldata callbackData_ +// ) internal view returns (uint256) { +// // Decode the merkle proof from the callback data +// (bytes32[] memory proof, uint256 allocatedAmount) = +// abi.decode(callbackData_, (bytes32[], uint256)); + +// // Get the leaf for the buyer +// bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_, allocatedAmount)))); + +// // Validate the merkle proof +// if (!MerkleProof.verify(proof, merkleRoot, leaf)) { +// revert Callback_NotAuthorized(); +// } + +// // Return the allocated amount for the buyer +// return allocatedAmount; +// } + +// function _canBuy(address buyer_, uint256 amount_, uint256 allocatedAmount_) internal { +// // Check if the buyer has already spent their limit +// if (buyerSpent[buyer_] + amount_ > allocatedAmount_) { +// revert Callback_ExceedsLimit(); +// } + +// // Update the buyer spent amount +// buyerSpent[buyer_] += amount_; +// } + +// // ========== ADMIN FUNCTIONS ========== // + +// /// @notice Sets the merkle root for the allowlist +// /// This function can be called by the owner to update the merkle root after `onCreate()`. +// /// @dev This function performs the following: +// /// - Performs validation +// /// - Sets the merkle root +// /// - Emits a MerkleRootSet event +// /// +// /// This function reverts if: +// /// - The caller is not the owner +// /// - The auction has not been registered +// /// - The auction has been completed +// /// +// /// @param merkleRoot_ The new merkle root +// function setMerkleRoot( +// bytes32 merkleRoot_ +// ) external onlyOwner { +// // Revert if onCreate has not been called +// if (lotId == type(uint96).max) { +// revert Callback_InvalidState(); +// } + +// // Revert if the auction has been completed already +// if (auctionComplete) { +// revert Callback_InvalidState(); +// } + +// merkleRoot = merkleRoot_; + +// emit MerkleRootSet(merkleRoot_); +// } +// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol index 2e2dbe8b..bebe4e88 100644 --- a/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol +++ b/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol @@ -1,156 +1,156 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; +// import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; -import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; +// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; /// @notice Allowlist version of the Baseline Axis Launch callback. /// @notice This version allows for a merkle tree to be used to determine which addresses are allowed to participate. However, the amount of quote tokens they can spend is not limited. -contract BALwithAllowlist is BaselineAxisLaunch { - // ========== ERRORS ========== // - - /// @notice Error message when the callback state does not support the action - error Callback_InvalidState(); - - // ========== EVENTS ========== // - - /// @notice Emitted when the merkle root is set - event MerkleRootSet(bytes32 merkleRoot); - - // ========== STATE VARIABLES ========== // - - /// @notice The root of the merkle tree that represents the allowlist - /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree - /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. - bytes32 public merkleRoot; - - // ========== CONSTRUCTOR ========== // - - // PERMISSIONS - // onCreate: true - // onCancel: true - // onCurate: true - // onPurchase: false - // onBid: true - // onSettle: true - // receiveQuoteTokens: true - // sendBaseTokens: true - // Contract prefix should be: 11101111 = 0xEF - - constructor( - address auctionHouse_, - address baselineKernel_, - address reserve_, - address owner_ - ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - - // ========== CALLBACK FUNCTIONS ========== // - - /// @inheritdoc BaselineAxisLaunch - /// @dev This function reverts if: - /// - `allowlistData_` is not of the correct length - /// - /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root - function __onCreate( - uint96, - address, - address, - address, - uint256, - bool, - bytes memory allowlistData_ - ) internal virtual override { - // Check that the parameters are of the correct length - if (allowlistData_.length != 32) { - revert Callback_InvalidParams(); - } - - // Decode the merkle root from the callback data - bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); - - // Set the merkle root - merkleRoot = merkleRootParams; - emit MerkleRootSet(merkleRoot); - } - - /// @inheritdoc BaselineAxisLaunch - /// - /// @param callbackData_ abi-encoded data: (bytes32[]) representing the merkle proof - function _onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual override { - // Validate that the buyer is allowed to participate - _canParticipate(buyer_, callbackData_); - - // Call any additional implementation-specific logic - __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); - } - - /// @notice Override this function to implement additional functionality for the `onBid` callback - /// - /// @param lotId_ The ID of the lot - /// @param bidId_ The ID of the bid - /// @param buyer_ The address of the buyer - /// @param amount_ The amount of quote tokens - /// @param callbackData_ The callback data - function __onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual {} - - // ========== INTERNAL FUNCTIONS ========== // - - function _canParticipate(address buyer_, bytes calldata callbackData_) internal view { - // Decode the merkle proof from the callback data - bytes32[] memory proof = abi.decode(callbackData_, (bytes32[])); - - // Get the leaf for the buyer - bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_)))); - - // Validate the merkle proof - if (!MerkleProof.verify(proof, merkleRoot, leaf)) { - revert Callback_NotAuthorized(); - } - } - - // ========== ADMIN FUNCTIONS ========== // - - /// @notice Sets the merkle root for the allowlist - /// This function can be called by the owner to update the merkle root after `onCreate()`. - /// @dev This function performs the following: - /// - Performs validation - /// - Sets the merkle root - /// - Emits a MerkleRootSet event - /// - /// This function reverts if: - /// - The caller is not the owner - /// - The auction has not been registered - /// - The auction has been completed - /// - /// @param merkleRoot_ The new merkle root - function setMerkleRoot( - bytes32 merkleRoot_ - ) external onlyOwner { - // Revert if onCreate has not been called - if (lotId == type(uint96).max) { - revert Callback_InvalidState(); - } - - // Revert if the auction has been completed already - if (auctionComplete) { - revert Callback_InvalidState(); - } - - merkleRoot = merkleRoot_; - - emit MerkleRootSet(merkleRoot_); - } -} +// contract BALwithAllowlist is BaselineAxisLaunch { +// // ========== ERRORS ========== // + +// /// @notice Error message when the callback state does not support the action +// error Callback_InvalidState(); + +// // ========== EVENTS ========== // + +// /// @notice Emitted when the merkle root is set +// event MerkleRootSet(bytes32 merkleRoot); + +// // ========== STATE VARIABLES ========== // + +// /// @notice The root of the merkle tree that represents the allowlist +// /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree +// /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. +// bytes32 public merkleRoot; + +// // ========== CONSTRUCTOR ========== // + +// // PERMISSIONS +// // onCreate: true +// // onCancel: true +// // onCurate: true +// // onPurchase: false +// // onBid: true +// // onSettle: true +// // receiveQuoteTokens: true +// // sendBaseTokens: true +// // Contract prefix should be: 11101111 = 0xEF + +// constructor( +// address auctionHouse_, +// address baselineKernel_, +// address reserve_, +// address owner_ +// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} + +// // ========== CALLBACK FUNCTIONS ========== // + +// /// @inheritdoc BaselineAxisLaunch +// /// @dev This function reverts if: +// /// - `allowlistData_` is not of the correct length +// /// +// /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root +// function __onCreate( +// uint96, +// address, +// address, +// address, +// uint256, +// bool, +// bytes memory allowlistData_ +// ) internal virtual override { +// // Check that the parameters are of the correct length +// if (allowlistData_.length != 32) { +// revert Callback_InvalidParams(); +// } + +// // Decode the merkle root from the callback data +// bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); + +// // Set the merkle root +// merkleRoot = merkleRootParams; +// emit MerkleRootSet(merkleRoot); +// } + +// /// @inheritdoc BaselineAxisLaunch +// /// +// /// @param callbackData_ abi-encoded data: (bytes32[]) representing the merkle proof +// function _onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual override { +// // Validate that the buyer is allowed to participate +// _canParticipate(buyer_, callbackData_); + +// // Call any additional implementation-specific logic +// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); +// } + +// /// @notice Override this function to implement additional functionality for the `onBid` callback +// /// +// /// @param lotId_ The ID of the lot +// /// @param bidId_ The ID of the bid +// /// @param buyer_ The address of the buyer +// /// @param amount_ The amount of quote tokens +// /// @param callbackData_ The callback data +// function __onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual {} + +// // ========== INTERNAL FUNCTIONS ========== // + +// function _canParticipate(address buyer_, bytes calldata callbackData_) internal view { +// // Decode the merkle proof from the callback data +// bytes32[] memory proof = abi.decode(callbackData_, (bytes32[])); + +// // Get the leaf for the buyer +// bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_)))); + +// // Validate the merkle proof +// if (!MerkleProof.verify(proof, merkleRoot, leaf)) { +// revert Callback_NotAuthorized(); +// } +// } + +// // ========== ADMIN FUNCTIONS ========== // + +// /// @notice Sets the merkle root for the allowlist +// /// This function can be called by the owner to update the merkle root after `onCreate()`. +// /// @dev This function performs the following: +// /// - Performs validation +// /// - Sets the merkle root +// /// - Emits a MerkleRootSet event +// /// +// /// This function reverts if: +// /// - The caller is not the owner +// /// - The auction has not been registered +// /// - The auction has been completed +// /// +// /// @param merkleRoot_ The new merkle root +// function setMerkleRoot( +// bytes32 merkleRoot_ +// ) external onlyOwner { +// // Revert if onCreate has not been called +// if (lotId == type(uint96).max) { +// revert Callback_InvalidState(); +// } + +// // Revert if the auction has been completed already +// if (auctionComplete) { +// revert Callback_InvalidState(); +// } + +// merkleRoot = merkleRoot_; + +// emit MerkleRootSet(merkleRoot_); +// } +// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol index fecf405a..11fda2fa 100644 --- a/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol +++ b/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol @@ -1,101 +1,101 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; -import {BALwithAllowlist} from "./BALwithAllowlist.sol"; +// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; +// import {BALwithAllowlist} from "./BALwithAllowlist.sol"; /// @notice Capped allowlist version of the Baseline Axis Launch callback. /// @notice This version allows for each address in the Merkle tree to have a standard amount of quote tokens they can spend. -contract BALwithCappedAllowlist is BALwithAllowlist { - // ========== ERRORS ========== // - - /// @notice Error message when the bid amount exceeds the limit assigned to a buyer - error Callback_ExceedsLimit(); - - // ========== STATE VARIABLES ========== // - - /// @notice The maximum amount a buyer can spend - uint256 public buyerLimit; - - /// @notice Tracks the cumulative amount spent by a buyer - mapping(address => uint256) public buyerSpent; - - // ========== CONSTRUCTOR ========== // - - // PERMISSIONS - // onCreate: true - // onCancel: true - // onCurate: true - // onPurchase: false - // onBid: true - // onSettle: true - // receiveQuoteTokens: true - // sendBaseTokens: true - // Contract prefix should be: 11101111 = 0xEF - - constructor( - address auctionHouse_, - address baselineKernel_, - address reserve_, - address owner_ - ) BALwithAllowlist(auctionHouse_, baselineKernel_, reserve_, owner_) {} - - // ========== CALLBACK FUNCTIONS ========== // - - /// @inheritdoc BaselineAxisLaunch - /// @dev This function reverts if: - /// - `allowlistData_` is not of the correct length - /// - /// @param allowlistData_ abi-encoded data: (bytes32, uint256) representing the merkle root and buyer limit - function __onCreate( - uint96, - address, - address, - address, - uint256, - bool, - bytes memory allowlistData_ - ) internal override { - // Check that the parameters are of the correct length - if (allowlistData_.length != 64) { - revert Callback_InvalidParams(); - } - - // Decode the merkle root from the callback data - (bytes32 merkleRoot_, uint256 buyerLimit_) = abi.decode(allowlistData_, (bytes32, uint256)); - - // Revert if buyer limit is 0, should just use regular allowlist version - if (buyerLimit_ == 0) revert Callback_InvalidParams(); - - // Set the merkle root and buyer limit - merkleRoot = merkleRoot_; - buyerLimit = buyerLimit_; - emit MerkleRootSet(merkleRoot); - } - - /// @inheritdoc BALwithAllowlist - /// @dev This function reverts if: - /// - The buyer has already spent their limit - function __onBid( - uint96, - uint64, - address buyer_, - uint256 amount_, - bytes calldata - ) internal override { - // Validate that the buyer is allowed to participate - _canBuy(buyer_, amount_); - } - - // ========== INTERNAL FUNCTIONS ========== // - - function _canBuy(address buyer_, uint256 amount_) internal { - // Check if the buyer has already spent their limit - if (buyerSpent[buyer_] + amount_ > buyerLimit) { - revert Callback_ExceedsLimit(); - } - - // Update the buyer spent amount - buyerSpent[buyer_] += amount_; - } -} +// contract BALwithCappedAllowlist is BALwithAllowlist { +// // ========== ERRORS ========== // + +// /// @notice Error message when the bid amount exceeds the limit assigned to a buyer +// error Callback_ExceedsLimit(); + +// // ========== STATE VARIABLES ========== // + +// /// @notice The maximum amount a buyer can spend +// uint256 public buyerLimit; + +// /// @notice Tracks the cumulative amount spent by a buyer +// mapping(address => uint256) public buyerSpent; + +// // ========== CONSTRUCTOR ========== // + +// // PERMISSIONS +// // onCreate: true +// // onCancel: true +// // onCurate: true +// // onPurchase: false +// // onBid: true +// // onSettle: true +// // receiveQuoteTokens: true +// // sendBaseTokens: true +// // Contract prefix should be: 11101111 = 0xEF + +// constructor( +// address auctionHouse_, +// address baselineKernel_, +// address reserve_, +// address owner_ +// ) BALwithAllowlist(auctionHouse_, baselineKernel_, reserve_, owner_) {} + +// // ========== CALLBACK FUNCTIONS ========== // + +// /// @inheritdoc BaselineAxisLaunch +// /// @dev This function reverts if: +// /// - `allowlistData_` is not of the correct length +// /// +// /// @param allowlistData_ abi-encoded data: (bytes32, uint256) representing the merkle root and buyer limit +// function __onCreate( +// uint96, +// address, +// address, +// address, +// uint256, +// bool, +// bytes memory allowlistData_ +// ) internal override { +// // Check that the parameters are of the correct length +// if (allowlistData_.length != 64) { +// revert Callback_InvalidParams(); +// } + +// // Decode the merkle root from the callback data +// (bytes32 merkleRoot_, uint256 buyerLimit_) = abi.decode(allowlistData_, (bytes32, uint256)); + +// // Revert if buyer limit is 0, should just use regular allowlist version +// if (buyerLimit_ == 0) revert Callback_InvalidParams(); + +// // Set the merkle root and buyer limit +// merkleRoot = merkleRoot_; +// buyerLimit = buyerLimit_; +// emit MerkleRootSet(merkleRoot); +// } + +// /// @inheritdoc BALwithAllowlist +// /// @dev This function reverts if: +// /// - The buyer has already spent their limit +// function __onBid( +// uint96, +// uint64, +// address buyer_, +// uint256 amount_, +// bytes calldata +// ) internal override { +// // Validate that the buyer is allowed to participate +// _canBuy(buyer_, amount_); +// } + +// // ========== INTERNAL FUNCTIONS ========== // + +// function _canBuy(address buyer_, uint256 amount_) internal { +// // Check if the buyer has already spent their limit +// if (buyerSpent[buyer_] + amount_ > buyerLimit) { +// revert Callback_ExceedsLimit(); +// } + +// // Update the buyer spent amount +// buyerSpent[buyer_] += amount_; +// } +// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol index 95c1bf56..e82b1245 100644 --- a/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol +++ b/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; -import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; +// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; /// @notice Generic interface for tokens that implement a balanceOf function (includes ERC-20 and ERC-721) interface ITokenBalance { @@ -15,119 +15,119 @@ interface ITokenBalance { /// @notice Allowlist contract that checks if a user's balance of a token is above a threshold /// @dev This shouldn't be used with liquid, transferable ERC-20s because it can easily be bypassed via flash loans or other swap mechanisms /// @dev The intent is to use this with non-transferable tokens (e.g. vote escrow) or illiquid tokens that are not as easily manipulated, e.g. community NFTs -contract BALwithTokenAllowlist is BaselineAxisLaunch { - // ========== ERRORS ========== // - - // ========== EVENTS ========== // - - // ========== STATE VARIABLES ========== // - - struct TokenCheck { - ITokenBalance token; - uint256 threshold; - } - - /// @notice Stores the token and balance threshold for the lot - TokenCheck public tokenCheck; - - // ========== CONSTRUCTOR ========== // - - // PERMISSIONS - // onCreate: true - // onCancel: true - // onCurate: true - // onPurchase: false - // onBid: true - // onSettle: true - // receiveQuoteTokens: true - // sendBaseTokens: true - // Contract prefix should be: 11101111 = 0xEF - - constructor( - address auctionHouse_, - address baselineKernel_, - address reserve_, - address owner_ - ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - - // ========== CALLBACK FUNCTIONS ========== // - - /// @inheritdoc BaselineAxisLaunch - /// @dev This function reverts if: - /// - `allowlistData_` is not of the correct length - /// - /// @param allowlistData_ abi-encoded data: (ITokenBalance, uint96) representing the token contract and minimum balance - function __onCreate( - uint96, - address, - address, - address, - uint256, - bool, - bytes memory allowlistData_ - ) internal virtual override { - // Check that the parameters are of the correct length - if (allowlistData_.length != 64) { - revert Callback_InvalidParams(); - } - - // Decode the params to get the token contract and balance threshold - (ITokenBalance token, uint96 threshold) = - abi.decode(allowlistData_, (ITokenBalance, uint96)); - - // Token must be a contract - if (address(token).code.length == 0) revert Callback_InvalidParams(); - - // Try to get balance for token, revert if it fails - try token.balanceOf(address(this)) returns (uint256) {} - catch { - revert Callback_InvalidParams(); - } - - // Set the lot check - tokenCheck = TokenCheck(token, threshold); - } - - /// @inheritdoc BaselineAxisLaunch - /// - /// @param callbackData_ abi-encoded data - function _onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual override { - // Validate that the buyer is allowed to participate - _canParticipate(buyer_); - - // Call any additional implementation-specific logic - __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); - } - - /// @notice Override this function to implement additional functionality for the `onBid` callback - /// - /// @param lotId_ The ID of the lot - /// @param bidId_ The ID of the bid - /// @param buyer_ The address of the buyer - /// @param amount_ The amount of quote tokens - /// @param callbackData_ The callback data - function __onBid( - uint96 lotId_, - uint64 bidId_, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual {} - - // ========== INTERNAL FUNCTIONS ========== // - - function _canParticipate( - address buyer_ - ) internal view { - // Check if the buyer's balance is above the threshold - if (tokenCheck.token.balanceOf(buyer_) < tokenCheck.threshold) { - revert Callback_NotAuthorized(); - } - } -} +// contract BALwithTokenAllowlist is BaselineAxisLaunch { +// // ========== ERRORS ========== // + +// // ========== EVENTS ========== // + +// // ========== STATE VARIABLES ========== // + +// struct TokenCheck { +// ITokenBalance token; +// uint256 threshold; +// } + +// /// @notice Stores the token and balance threshold for the lot +// TokenCheck public tokenCheck; + +// // ========== CONSTRUCTOR ========== // + +// // PERMISSIONS +// // onCreate: true +// // onCancel: true +// // onCurate: true +// // onPurchase: false +// // onBid: true +// // onSettle: true +// // receiveQuoteTokens: true +// // sendBaseTokens: true +// // Contract prefix should be: 11101111 = 0xEF + +// constructor( +// address auctionHouse_, +// address baselineKernel_, +// address reserve_, +// address owner_ +// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} + +// // ========== CALLBACK FUNCTIONS ========== // + +// /// @inheritdoc BaselineAxisLaunch +// /// @dev This function reverts if: +// /// - `allowlistData_` is not of the correct length +// /// +// /// @param allowlistData_ abi-encoded data: (ITokenBalance, uint96) representing the token contract and minimum balance +// function __onCreate( +// uint96, +// address, +// address, +// address, +// uint256, +// bool, +// bytes memory allowlistData_ +// ) internal virtual override { +// // Check that the parameters are of the correct length +// if (allowlistData_.length != 64) { +// revert Callback_InvalidParams(); +// } + +// // Decode the params to get the token contract and balance threshold +// (ITokenBalance token, uint96 threshold) = +// abi.decode(allowlistData_, (ITokenBalance, uint96)); + +// // Token must be a contract +// if (address(token).code.length == 0) revert Callback_InvalidParams(); + +// // Try to get balance for token, revert if it fails +// try token.balanceOf(address(this)) returns (uint256) {} +// catch { +// revert Callback_InvalidParams(); +// } + +// // Set the lot check +// tokenCheck = TokenCheck(token, threshold); +// } + +// /// @inheritdoc BaselineAxisLaunch +// /// +// /// @param callbackData_ abi-encoded data +// function _onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual override { +// // Validate that the buyer is allowed to participate +// _canParticipate(buyer_); + +// // Call any additional implementation-specific logic +// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); +// } + +// /// @notice Override this function to implement additional functionality for the `onBid` callback +// /// +// /// @param lotId_ The ID of the lot +// /// @param bidId_ The ID of the bid +// /// @param buyer_ The address of the buyer +// /// @param amount_ The amount of quote tokens +// /// @param callbackData_ The callback data +// function __onBid( +// uint96 lotId_, +// uint64 bidId_, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual {} + +// // ========== INTERNAL FUNCTIONS ========== // + +// function _canParticipate( +// address buyer_ +// ) internal view { +// // Check if the buyer's balance is above the threshold +// if (tokenCheck.token.balanceOf(buyer_) < tokenCheck.threshold) { +// revert Callback_NotAuthorized(); +// } +// } +// } diff --git a/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol b/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol index dbcd691f..043c19c4 100644 --- a/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol +++ b/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol @@ -1,962 +1,962 @@ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.19; -// Axis dependencies -import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; -import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; -import { - Keycode as AxisKeycode, - keycodeFromVeecode, - fromKeycode as fromAxisKeycode -} from "@axis-core-1.0.4/modules/Keycode.sol"; -import {Module as AxisModule} from "@axis-core-1.0.4/modules/Modules.sol"; -import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; -import {Transfer} from "@axis-core-1.0.4/lib/Transfer.sol"; - -// Baseline dependencies -import { - Kernel, - Policy, - Keycode as BaselineKeycode, - toKeycode as toBaselineKeycode, - Permissions as BaselinePermissions -} from "./lib/Kernel.sol"; -import {Position, Range, IBPOOLv1, IUniswapV3Pool} from "./lib/IBPOOL.sol"; -import {ICREDTv1} from "./lib/ICREDT.sol"; -import {ILOOPSv1} from "./lib/ILOOPS.sol"; - -// Other libraries -import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; -import {SqrtPriceMath} from "../../../lib/uniswap-v3/SqrtPriceMath.sol"; -import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; +// // Axis dependencies +// import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; +// import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; +// import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; +// import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; +// import { +// Keycode as AxisKeycode, +// keycodeFromVeecode, +// fromKeycode as fromAxisKeycode +// } from "@axis-core-1.0.4/modules/Keycode.sol"; +// import {Module as AxisModule} from "@axis-core-1.0.4/modules/Modules.sol"; +// import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; +// import {Transfer} from "@axis-core-1.0.4/lib/Transfer.sol"; + +// // Baseline dependencies +// import { +// Kernel, +// Policy, +// Keycode as BaselineKeycode, +// toKeycode as toBaselineKeycode, +// Permissions as BaselinePermissions +// } from "./lib/Kernel.sol"; +// import {Position, Range, IBPOOLv1, IUniswapV3Pool} from "./lib/IBPOOL.sol"; +// import {ICREDTv1} from "./lib/ICREDT.sol"; +// import {ILOOPSv1} from "./lib/ILOOPS.sol"; + +// // Other libraries +// import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; +// import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; +// import {SqrtPriceMath} from "../../../lib/uniswap-v3/SqrtPriceMath.sol"; +// import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; /// @notice Axis auction callback to initialize a Baseline token using proceeds from a batch auction. /// @dev This contract combines Baseline's InitializeProtocol Policy and Axis' Callback functionality to build an Axis auction callback specific to Baseline V2 token launches /// It is designed to be used with a single auction and Baseline pool -contract BaselineAxisLaunch is BaseCallback, Policy, Owned { - using FixedPointMathLib for uint256; +// contract BaselineAxisLaunch is BaseCallback, Policy, Owned { +// using FixedPointMathLib for uint256; - // ========== ERRORS ========== // +// // ========== ERRORS ========== // - /// @notice The address of the base token (passed in the `onCreate` callback) does not match the address of the bAsset that the callback was initialized with - error Callback_Params_BAssetTokenMismatch(address baseToken_, address bAsset_); +// /// @notice The address of the base token (passed in the `onCreate` callback) does not match the address of the bAsset that the callback was initialized with +// error Callback_Params_BAssetTokenMismatch(address baseToken_, address bAsset_); - /// @notice The address of the quote token (passed in the `onCreate` callback) does not match the address of the reserve that the callback was initialized with - error Callback_Params_ReserveTokenMismatch(address quoteToken_, address reserve_); +// /// @notice The address of the quote token (passed in the `onCreate` callback) does not match the address of the reserve that the callback was initialized with +// error Callback_Params_ReserveTokenMismatch(address quoteToken_, address reserve_); - /// @notice The auction format is not supported - error Callback_Params_UnsupportedAuctionFormat(); +// /// @notice The auction format is not supported +// error Callback_Params_UnsupportedAuctionFormat(); - /// @notice The pool fee tier is not supported - error Callback_Params_UnsupportedPoolFeeTier(); +// /// @notice The pool fee tier is not supported +// error Callback_Params_UnsupportedPoolFeeTier(); - /// @notice The anchor tick width is invalid - error Callback_Params_InvalidAnchorTickWidth(); +// /// @notice The anchor tick width is invalid +// error Callback_Params_InvalidAnchorTickWidth(); - /// @notice The discovery tick width is invalid - error Callback_Params_InvalidDiscoveryTickWidth(); +// /// @notice The discovery tick width is invalid +// error Callback_Params_InvalidDiscoveryTickWidth(); - /// @notice The floor range gap is invalid - error Callback_Params_InvalidFloorRangeGap(); +// /// @notice The floor range gap is invalid +// error Callback_Params_InvalidFloorRangeGap(); - /// @notice The anchor tick upper is invalid - error Callback_Params_InvalidAnchorTickUpper(); +// /// @notice The anchor tick upper is invalid +// error Callback_Params_InvalidAnchorTickUpper(); - /// @notice The pool target tick is invalid - /// @dev The pool target tick must be >= `anchorRangeLower` and <= `anchorRangeUpper` - /// - /// @param anchorRangeLower The lower tick of the anchor range - /// @param anchorRangeUpper The upper tick of the anchor range - error Callback_Params_InvalidPoolTargetTick(int24 anchorRangeLower, int24 anchorRangeUpper); +// /// @notice The pool target tick is invalid +// /// @dev The pool target tick must be >= `anchorRangeLower` and <= `anchorRangeUpper` +// /// +// /// @param anchorRangeLower The lower tick of the anchor range +// /// @param anchorRangeUpper The upper tick of the anchor range +// error Callback_Params_InvalidPoolTargetTick(int24 anchorRangeLower, int24 anchorRangeUpper); - /// @notice One of the ranges is out of bounds - error Callback_Params_RangeOutOfBounds(); +// /// @notice One of the ranges is out of bounds +// error Callback_Params_RangeOutOfBounds(); - /// @notice The floor reserves percent is invalid - error Callback_Params_InvalidFloorReservesPercent(); +// /// @notice The floor reserves percent is invalid +// error Callback_Params_InvalidFloorReservesPercent(); - /// @notice The pool percent is invalid - error Callback_Params_InvalidPoolPercent(); +// /// @notice The pool percent is invalid +// error Callback_Params_InvalidPoolPercent(); - /// @notice The recipient address is invalid - error Callback_Params_InvalidRecipient(); +// /// @notice The recipient address is invalid +// error Callback_Params_InvalidRecipient(); - /// @notice The auction tied to this callbacks contract has already been completed - error Callback_AlreadyComplete(); +// /// @notice The auction tied to this callbacks contract has already been completed +// error Callback_AlreadyComplete(); - /// @notice The required funds were not sent to this callbacks contract - error Callback_MissingFunds(); +// /// @notice The required funds were not sent to this callbacks contract +// error Callback_MissingFunds(); - /// @notice The initialization is invalid - error Callback_InvalidInitialization(); +// /// @notice The initialization is invalid +// error Callback_InvalidInitialization(); - /// @notice The capacity ratio is invalid - /// - /// @param capacityRatio The ratio of the pool capacity to the circulating supply - error Callback_InvalidCapacityRatio(uint256 capacityRatio); +// /// @notice The capacity ratio is invalid +// /// +// /// @param capacityRatio The ratio of the pool capacity to the circulating supply +// error Callback_InvalidCapacityRatio(uint256 capacityRatio); - /// @notice The pool price is lower than the auction price - /// - /// @param currentTick The current tick of the pool - /// @param auctionTick The tick corresponding to the auction price - error Callback_PoolLessThanAuctionPrice(int24 currentTick, int24 auctionTick); +// /// @notice The pool price is lower than the auction price +// /// +// /// @param currentTick The current tick of the pool +// /// @param auctionTick The tick corresponding to the auction price +// error Callback_PoolLessThanAuctionPrice(int24 currentTick, int24 auctionTick); - /// @notice The BPOOL reserve token does not match the configured `RESERVE` address - error Callback_BPOOLReserveMismatch(); +// /// @notice The BPOOL reserve token does not match the configured `RESERVE` address +// error Callback_BPOOLReserveMismatch(); - /// @notice The address of the BPOOL is higher than the RESERVE token address, when it must be lower - error Callback_BPOOLInvalidAddress(); +// /// @notice The address of the BPOOL is higher than the RESERVE token address, when it must be lower +// error Callback_BPOOLInvalidAddress(); - /// @notice The caller to the Uniswap V3 swap callback is invalid - error Callback_Swap_InvalidCaller(); +// /// @notice The caller to the Uniswap V3 swap callback is invalid +// error Callback_Swap_InvalidCaller(); - /// @notice The case for the Uniswap V3 swap callback is invalid - error Callback_Swap_InvalidCase(); - - // ========== EVENTS ========== // - - event LiquidityDeployed( - int24 floorTickLower, int24 anchorTickUpper, uint128 floorLiquidity, uint128 anchorLiquidity - ); - - // ========== DATA STRUCTURES ========== // - - /// @notice Data struct for the onCreate callback - /// - /// @param recipient The address to receive proceeds that do not go to the pool - /// @param poolPercent The percentage of the proceeds to allocate to the pool, in basis points (1% = 100). The remainder will be sent to the `recipient`. - /// @param floorReservesPercent The percentage of the pool proceeds to allocate to the floor range, in basis points (1% = 100). The remainder will be allocated to the anchor range. - /// @param floorRangeGap The gap between the floor and anchor ranges, as a multiple of the pool tick spacing. - /// @param anchorTickU The upper tick of the anchor range. Validated against the calculated upper bound of the anchor range. This is provided off-chain to prevent front-running. - /// @param anchorTickWidth The width of the anchor tick range, as a multiple of the pool tick spacing. - /// @param poolTargetTick The target tick for the pool. This is provided off-chain to prevent front-running. - /// @param allowlistParams Additional parameters for an allowlist, passed to `__onCreate()` for further processing - struct CreateData { - address recipient; - uint24 poolPercent; - uint24 floorReservesPercent; - int24 floorRangeGap; - int24 anchorTickU; - int24 anchorTickWidth; - int24 poolTargetTick; - bytes allowlistParams; - } - - // ========== CONSTANTS ========== // - - /// @notice The minimum tick value - int24 internal constant _MIN_TICK = -887_272; - - /// @notice The maximum tick value - int24 internal constant _MAX_TICK = 887_272; - - /// @notice The value for 100% - // solhint-disable-next-line private-vars-leading-underscore - uint48 internal constant ONE_HUNDRED_PERCENT = 100e2; - - /// @notice The tick spacing width of the discovery range - int24 internal constant _DISCOVERY_TICK_SPACING_WIDTH = 350; - - // ========== STATE VARIABLES ========== // - - // Baseline Modules - // solhint-disable var-name-mixedcase - IBPOOLv1 public BPOOL; - ICREDTv1 public CREDT; - ILOOPSv1 public LOOPS; - - // Pool variables - ERC20 public immutable RESERVE; - // solhint-enable var-name-mixedcase - ERC20 public bAsset; - - // Axis Auction Variables - - /// @notice Lot ID of the auction for the baseline market. This callback only supports one lot. - /// @dev This value is initialised with the uint96 max value to indicate that it has not been set yet. - uint96 public lotId; - - /// @notice Indicates whether the auction is complete - /// @dev This is used to prevent the callback from being called multiple times. It is set in the `onSettle()` callback. - bool public auctionComplete; - - /// @notice The percentage of the proceeds to allocate to the pool - /// @dev This value is set in the `onCreate()` callback. - uint24 public poolPercent; - - /// @notice The percentage of the proceeds to allocate to the floor range - /// @dev This value is set in the `onCreate()` callback. - uint24 public floorReservesPercent; - - /// @notice The address to receive proceeds that do not go to the pool - /// @dev This value is set in the `onCreate()` callback. - address public recipient; - - /// @notice The target tick for the pool - /// @dev This value is set in the `onCreate()` callback. - int24 public poolTargetTick; - - // ========== CONSTRUCTOR ========== // - - /// @notice Constructor for BaselineAxisLaunch - /// - /// @param auctionHouse_ The AuctionHouse the callback is paired with - /// @param baselineKernel_ Address of the Baseline kernel - /// @param reserve_ Address of the reserve token. This should match the quote token for the auction lot. - /// @param owner_ Address of the owner of the contract. Must be the same as the eventual seller of the auction lot. - constructor( - address auctionHouse_, - address baselineKernel_, - address reserve_, - address owner_ - ) - BaseCallback( - auctionHouse_, - Callbacks.Permissions({ - onCreate: true, - onCancel: true, - onCurate: true, - onPurchase: false, - onBid: true, - onSettle: true, - receiveQuoteTokens: true, - sendBaseTokens: true - }) - ) - Policy(Kernel(baselineKernel_)) - Owned(owner_) - { - // Set lot ID to max uint(96) initially so it doesn't reference a lot - lotId = type(uint96).max; - - // Set the reserve token - RESERVE = ERC20(reserve_); - } - - // ========== POLICY FUNCTIONS ========== // - - /// @inheritdoc Policy - function configureDependencies() - external - override - onlyKernel - returns (BaselineKeycode[] memory dependencies) - { - BaselineKeycode bpool = toBaselineKeycode("BPOOL"); - BaselineKeycode credt = toBaselineKeycode("CREDT"); - BaselineKeycode loops = toBaselineKeycode("LOOPS"); - - // Populate the dependencies array - dependencies = new BaselineKeycode[](3); - dependencies[0] = bpool; - dependencies[1] = credt; - dependencies[2] = loops; - - // Set local values - BPOOL = IBPOOLv1(getModuleAddress(bpool)); - bAsset = ERC20(address(BPOOL)); - CREDT = ICREDTv1(getModuleAddress(credt)); - LOOPS = ILOOPSv1(getModuleAddress(loops)); - - // Require that the BPOOL's reserve token be the same as the callback's reserve token - if (address(BPOOL.reserve()) != address(RESERVE)) revert Callback_BPOOLReserveMismatch(); - } - - /// @inheritdoc Policy - function requestPermissions() - external - view - override - onlyKernel - returns (BaselinePermissions[] memory requests) - { - BaselineKeycode bpool = toBaselineKeycode("BPOOL"); - - requests = new BaselinePermissions[](6); - requests[0] = BaselinePermissions(bpool, BPOOL.addReservesTo.selector); - requests[1] = BaselinePermissions(bpool, BPOOL.addLiquidityTo.selector); - requests[2] = BaselinePermissions(bpool, BPOOL.burnAllBAssetsInContract.selector); - requests[3] = BaselinePermissions(bpool, BPOOL.mint.selector); - requests[4] = BaselinePermissions(bpool, BPOOL.setTicks.selector); - requests[5] = BaselinePermissions(bpool, BPOOL.setTransferLock.selector); - } - - // ========== MODIFIERS ========== // - - /// @notice Validates that the lot id matches the stored lot id - modifier onlyValidLot( - uint96 lotId_ - ) { - if (lotId_ != lotId) revert Callback_InvalidParams(); - _; - } - - /// @notice Validates that the auction is not already settled or cancelled - modifier onlyActiveLot() { - if (auctionComplete) revert Callback_AlreadyComplete(); - _; - } - - // ========== CALLBACK FUNCTIONS ========== // - - // CALLBACK PERMISSIONS - // onCreate: true - // onCancel: true - // onCurate: true - // onPurchase: false - // onBid: true - // onSettle: true - // receiveQuoteTokens: true - // sendBaseTokens: true - // Contract prefix should be: 11101111 = 0xEF - - /// @inheritdoc BaseCallback - /// @dev This function performs the following: - /// - Performs validation - /// - Sets the `lotId`, `percentReservesFloor`, `anchorTickWidth`, and `discoveryTickWidth` variables - /// - Calls the allowlist callback - /// - Performs a solvency check to ensure the pool can support the intended supply - /// - Mints the required bAsset tokens to the AuctionHouse - /// - /// This function has the following assumptions: - /// - Any Baseline credit allocations have been minted and allocated prior to auction creation (and this callback) - /// - /// This function reverts if: - /// - `seller_` is not the owner - /// - `baseToken_` is not the same as `bAsset` - /// - `quoteToken_` is not the same as `RESERVE` - /// - `baseToken_` is not lower than `quoteToken_` - /// - `recipient` is the zero address - /// - `lotId` is already set - /// - The pool fee tier is not supported - /// - The auction format is not supported - /// - The auction is not prefunded - /// - `CreateData.floorReservesPercent` is less than 10% or greater than 99% - /// - `CreateData.poolPercent` is less than 10% or greater than 100% - /// - `CreateData.floorRangeGap` is < 0 - /// - `CreateData.anchorTickWidth` is < 10 or > 50 - /// - `CreateData.anchorTickU` is not the same as the calculated value - /// - `CreateData.poolTargetTick` is not >= anchorRangeLower and < anchorRangeUpper - /// - Any of the tick ranges would exceed the tick bounds - /// - The pool tick is less than the auction price (in terms of ticks) - /// - The pool capacity is not sufficient to support the intended supply - function _onCreate( - uint96 lotId_, - address seller_, - address baseToken_, - address quoteToken_, - uint256 capacity_, - bool prefund_, - bytes calldata callbackData_ - ) internal override { - // Validate that the seller is the owner - // Otherwise this single-use callback could be used by anyone - if (seller_ != owner) { - revert Callback_NotAuthorized(); - } - - // Validate the base token is the baseline token - // and the quote token is the reserve - if (baseToken_ != address(bAsset)) { - revert Callback_Params_BAssetTokenMismatch(baseToken_, address(bAsset)); - } - if (quoteToken_ != address(RESERVE)) { - revert Callback_Params_ReserveTokenMismatch(quoteToken_, address(RESERVE)); - } - // Ensure the base token is lower than the quote token - if (address(bAsset) > address(RESERVE)) { - revert Callback_BPOOLInvalidAddress(); - } - - // Validate that the lot ID is not already set - if (lotId != type(uint96).max) revert Callback_InvalidParams(); - - // Decode the provided callback data (must be correctly formatted even if not using parts of it) - CreateData memory cbData = abi.decode(callbackData_, (CreateData)); - - // Validate that the recipient is not the zero address - if (cbData.recipient == address(0)) revert Callback_Params_InvalidRecipient(); - - // Validate that the pool fee tier is supported - // This callback only supports the 1% fee tier (tick spacing = 200) - // as other fee tiers are not supported by the Baseline pool - if (BPOOL.TICK_SPACING() != 200) revert Callback_Params_UnsupportedPoolFeeTier(); - - // Validate that the floor range gap is at least 0 - if (cbData.floorRangeGap < 0) revert Callback_Params_InvalidFloorRangeGap(); - - // Validate that the anchor tick width is at least 10 tick spacing and at most 50 - // Baseline supports only within this range - if (cbData.anchorTickWidth < 10 || cbData.anchorTickWidth > 50) { - revert Callback_Params_InvalidAnchorTickWidth(); - } - - // Validate that the floor reserves percent is between 10% and 90% - // If the floor reserves are too low, it can render `MarketMaking.slide()` inoperable - // If the floor reserves are too high, it can render `MarketMaking.sweep()` inoperable - // as the anchor and discovery liquidity will be too thin - if (cbData.floorReservesPercent < 10e2 || cbData.floorReservesPercent > 99e2) { - revert Callback_Params_InvalidFloorReservesPercent(); - } - - // Validate that the pool percent is at least 10% and at most 100% - if (cbData.poolPercent < 10e2 || cbData.poolPercent > 100e2) { - revert Callback_Params_InvalidPoolPercent(); - } - - // Auction must be prefunded for batch auctions (which is the only type supported with this callback), - // this can't fail because it's checked in the AH as well, but including for completeness - if (!prefund_) revert Callback_Params_UnsupportedAuctionFormat(); - - // Set the lot ID - lotId = lotId_; - - // Set the recipient - recipient = cbData.recipient; - - // Set the pool percent - poolPercent = cbData.poolPercent; - - // Set the floor reserves percent - floorReservesPercent = cbData.floorReservesPercent; - - // Only supports Fixed Price Batch Auctions initially - { - // Get the auction format - AxisKeycode auctionFormat = keycodeFromVeecode( - AxisModule(address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_))) - .VEECODE() - ); - - if (fromAxisKeycode(auctionFormat) != bytes5("FPBA")) { - revert Callback_Params_UnsupportedAuctionFormat(); - } - } - - // This contract can be extended with an allowlist for the auction - // Call a lower-level function where this information can be used - // We do this before token interactions to conform to CEI - __onCreate( - lotId_, seller_, baseToken_, quoteToken_, capacity_, prefund_, cbData.allowlistParams - ); - - // Set the ticks for the Baseline pool initially with the following assumptions: - // - The floor range is 1 tick spacing wide - // - The anchor range is `anchorTickWidth` tick spacings wide, above the floor range - // - The discovery range is `discoveryTickWidth` tick spacings wide, above the anchor range - // - The anchor range contains the active tick - // - The anchor range upper tick is the active tick rounded up to the nearest tick spacing - // - The other range boundaries are calculated accordingly - { - // Check that the anchor tick range upper bound is the same - // as the closest tick spacing boundary above the active tick on the BPOOL - // We check this value against a parameter instead of reading - // directly to avoid a situation where someone front-runs the - // auction creation transaction and moves the active tick - if (cbData.anchorTickU != BPOOL.getActiveTS()) { - revert Callback_Params_InvalidAnchorTickUpper(); - } - int24 anchorRangeUpper = cbData.anchorTickU; - - // Get the tick spacing from the pool - int24 tickSpacing = BPOOL.TICK_SPACING(); - - // Anchor range lower is the anchor tick width below the anchor range upper - int24 anchorRangeLower = anchorRangeUpper - cbData.anchorTickWidth * tickSpacing; - - // Validate that the pool target tick is within the anchor range - // The `_onSettle()` function will perform swaps (if necessary) to move the pool tick to the target tick in order to mitigate manipulation. - // The value must be in the anchor range and below the anchor upper tick (which is where the discovery range begins). - if ( - cbData.poolTargetTick < anchorRangeLower - || cbData.poolTargetTick >= anchorRangeUpper - ) { - revert Callback_Params_InvalidPoolTargetTick(anchorRangeLower, anchorRangeUpper); - } - poolTargetTick = cbData.poolTargetTick; - - // Set the anchor range - BPOOL.setTicks(Range.ANCHOR, anchorRangeLower, anchorRangeUpper); - - // Set the floor range - // The creator can provide the `floorRangeGap` to space the floor range from the anchor range - // If `floorRangeGap` is 0, the floor range will be directly below the anchor range - // The floor range is one tick spacing wide - int24 floorRangeUpper = anchorRangeLower - cbData.floorRangeGap * tickSpacing; - int24 floorRangeLower = floorRangeUpper - tickSpacing; - - BPOOL.setTicks(Range.FLOOR, floorRangeLower, floorRangeUpper); - - // Set the discovery range - int24 discoveryRangeUpper = - anchorRangeUpper + tickSpacing * _DISCOVERY_TICK_SPACING_WIDTH; - BPOOL.setTicks(Range.DISCOVERY, anchorRangeUpper, discoveryRangeUpper); - - // If the floor range lower tick (or any other above it) is below the min tick, it will cause problems - // If the discovery range upper tick (or any other below it) is above the max tick, it will cause problems - if (floorRangeLower < _MIN_TICK || discoveryRangeUpper > _MAX_TICK) { - revert Callback_Params_RangeOutOfBounds(); - } - } - - // Perform a pre-check to make sure the setup can be valid - // This avoids certain bad configurations that would lead to failed initializations - // Specifically, we check that the pool can support the intended supply - // factoring in the capacity, curator fee, and any additional spot or collateralized supply - // that already exists. - // We assume that the auction capacity will be completely filled. This can be guaranteed by - // setting the minFillPercent to 100e2 on the auction. - { - // Calculate the initial circulating supply (including collateralized supply) - uint256 initialCircSupply; - { - // Get the current supply values - uint256 totalSupply = bAsset.totalSupply(); // can use totalSupply here since no bAssets are in the pool yet - - // Calculate the maximum curator fee that can be paid - (,, uint48 curatorFeePerc,,) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); - uint256 curatorFee = (capacity_ * curatorFeePerc) / ONE_HUNDRED_PERCENT; - - // Capacity and curator fee have not yet been minted, so we add those - // Collateralized supply is already minted and included in total supply, so we do not need to add it - initialCircSupply = totalSupply + capacity_ + curatorFee; - } - - // Calculate the initial capacity of the pool based on the ticks set and the expected proceeds to deposit in the pool - uint256 initialCapacity; - { - // Get the fixed price from the auction module - // This value is in the number of reserve tokens per baseline token - uint256 auctionPrice; - { - auctionPrice = IFixedPriceBatch( - address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_)) - ).getAuctionData(lotId_).price; - } - - // Get the active tick from the pool and confirm it is >= the auction price corresponds to - { - // We do this to avoid a situation where buyers are disincentivized to bid on the auction - // Pool price is number of token1 (reserve) per token0 (bAsset), which is what we want, but it needs to be squared - (, int24 activeTick,,,,,) = BPOOL.pool().slot0(); - - // Calculate the tick for the auction price - // `getSqrtPriceX96` handles token ordering - // The resulting tick will incorporate any differences in decimals between the tokens - uint160 sqrtPriceX96 = SqrtPriceMath.getSqrtPriceX96( - address(RESERVE), address(bAsset), auctionPrice, 10 ** bAsset.decimals() - ); - int24 auctionTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); - - // Verify that the active tick is at least the auction tick - if (activeTick < auctionTick) { - revert Callback_PoolLessThanAuctionPrice(activeTick, auctionTick); - } - } - - uint256 poolProceeds = ( - _getExpectedProceeds(lotId_, capacity_, auctionPrice) * poolPercent - ) / ONE_HUNDRED_PERCENT; - - // Calculate the expected reserves for the floor and anchor ranges - uint256 floorReserves = (poolProceeds * floorReservesPercent) / ONE_HUNDRED_PERCENT; - uint256 anchorReserves = poolProceeds - floorReserves; - - // Calculate the expected capacity of the pool - // Skip discovery range since no reserves will be deposited in it - Position memory floor = BPOOL.getPosition(Range.FLOOR); - Position memory anchor = BPOOL.getPosition(Range.ANCHOR); - - uint256 floorCapacity = - BPOOL.getCapacityForReserves(floor.sqrtPriceL, floor.sqrtPriceU, floorReserves); - uint256 anchorCapacity = BPOOL.getCapacityForReserves( - anchor.sqrtPriceL, anchor.sqrtPriceU, anchorReserves - ); - - // Calculate the debt capacity at the floor range - uint256 debtCapacity = BPOOL.getCapacityForReserves( - floor.sqrtPriceL, - floor.sqrtPriceU, - CREDT.totalCreditIssued() + LOOPS.totalDebt() - ); - - // Calculate the total initial capacity of the pool - initialCapacity = debtCapacity + floorCapacity + anchorCapacity; - } - - // Verify the liquidity can support the intended supply - // and that there is no significant initial surplus - // - // If the solvency check is failing, it can be resolved by adjusting the following: - // - auction price (via the auction fixed price) - // - system liquidity (via the pool allocation and floor reserves allocation) - uint256 capacityRatio = initialCapacity.divWad(initialCircSupply); - if (capacityRatio < 100e16 || capacityRatio > 102e16) { - revert Callback_InvalidCapacityRatio(capacityRatio); - } - } - - // Unlock BPOOL transfers - BPOOL.setTransferLock(false); - - // Mint the capacity of baseline tokens to the auction house to prefund the auction - BPOOL.mint(msg.sender, capacity_); - - // Lock BPOOL transfers - // This is to prevent any transfers of bAssets until the auction is settled - // The BPOOL will need to be manually unlocked prior to the auction being cancelled or settled - BPOOL.setTransferLock(true); - } - - /// @notice Override this function to implement allowlist functionality - function __onCreate( - uint96 lotId_, - address seller_, - address baseToken_, - address quoteToken_, - uint256 capacity_, - bool prefund_, - bytes memory allowlistData_ - ) internal virtual {} - - /// @inheritdoc BaseCallback - /// @dev This function performs the following: - /// - Performs validation - /// - Burns the refunded bAsset tokens - /// - /// This function has the following assumptions: - /// - BaseCallback has already validated the lot ID - /// - The AuctionHouse has already sent the correct amount of bAsset tokens - /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of BPOOL tokens from the AuctionHouse to the callback - /// - /// This function reverts if: - /// - `lotId_` is not the same as the stored `lotId` - /// - The auction is already complete - /// - Sufficient quantity of `bAsset` have not been sent to the callback - function _onCancel( - uint96 lotId_, - uint256 refund_, - bool, - bytes calldata - ) internal override onlyValidLot(lotId_) onlyActiveLot { - // Burn any refunded tokens (all auctions are prefunded) - // Verify that the callback received the correct amount of bAsset tokens - if (bAsset.balanceOf(address(this)) < refund_) revert Callback_MissingFunds(); - - // Set the auction lot to be cancelled - auctionComplete = true; - - // Unlock BPOOL transfers - BPOOL.setTransferLock(false); - - // Send tokens to BPOOL and then burn - Transfer.transfer(bAsset, address(BPOOL), refund_, false); - BPOOL.burnAllBAssetsInContract(); - - // Lock BPOOL transfers - BPOOL.setTransferLock(true); - } - - /// @inheritdoc BaseCallback - /// @dev This function performs the following: - /// - Performs validation - /// - /// This function has the following assumptions: - /// - BaseCallback has already validated the lot ID - /// - /// This function reverts if: - /// - `lotId_` is not the same as the stored `lotId` - /// - The curator fee is non-zero - function _onCurate( - uint96 lotId_, - uint256 curatorFee_, - bool, - bytes calldata - ) internal override onlyValidLot(lotId_) onlyActiveLot { - // Mint tokens for curator fee if it's not zero - if (curatorFee_ > 0) { - // Unlock BPOOL transfers - BPOOL.setTransferLock(false); - - BPOOL.mint(msg.sender, curatorFee_); - - // Lock BPOOL transfers - BPOOL.setTransferLock(true); - } - } - - /// @inheritdoc BaseCallback - /// @dev Not implemented since atomic auctions are not supported - function _onPurchase( - uint96, - address, - uint256, - uint256, - bool, - bytes calldata - ) internal pure override { - revert Callback_NotImplemented(); - } - - /// @inheritdoc BaseCallback - /// @dev No logic is needed for this function here, but it can be overridden by a lower-level contract to provide allowlist functionality - function _onBid( - uint96 lotId_, - uint64 bidId, - address buyer_, - uint256 amount_, - bytes calldata callbackData_ - ) internal virtual override {} - - /// @inheritdoc BaseCallback - /// @dev This function performs the following: - /// - Performs validation - /// - Sets the auction as complete - /// - Burns any refunded bAsset tokens - /// - Ensures that the pool is at the correct price - /// - Deploys reserves and liquidity into the Baseline pool - /// - Performs a solvency check to ensure the pool can support the supply - /// - Transfers any remaining proceeds (reserves) to the recipient - /// - /// Next steps: - /// - Activate the market making and credit facility policies in the Baseline stack, which cannot be enabled before the auction is settled and the pool is initialized - /// - /// This function has the following assumptions: - /// - BaseCallback has already validated the lot ID - /// - The AuctionHouse has already sent the correct amount of quote tokens (proceeds) - /// - The AuctionHouse has already sent the correct amount of refunded base tokens - /// - The AuctionHouse is pre-funded, so does not require additional base tokens (bAssets) to be supplied - /// - No new Baseline credit allocations have been made since the auction was created (and `onCreate` was called) - /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of refunded BPOOL tokens from the AuctionHouse to the callback - /// - /// This function reverts if: - /// - `lotId_` is not the same as the stored `lotId` - /// - The auction is already complete - /// - The reported proceeds received are less than the reserve balance - /// - The reported refund received is less than the bAsset balance - /// - The pool price is not at the target price - /// - The pool capacity is not sufficient to support the intended supply - /// - /// Note that while the solvency check in both `onCreate` and `onSettle` are consistent, if the auction is not fully subscribed (and hence there is a refund), it can cause the solvency check to fail in `onSettle`. - function _onSettle( - uint96 lotId_, - uint256 proceeds_, - uint256 refund_, - bytes calldata - ) internal virtual override onlyValidLot(lotId_) onlyActiveLot { - // Validate that the callback received the correct amount of proceeds - // As this is a single-use contract, reserve balance is likely 0 prior, but extra funds will not affect it - if (proceeds_ > RESERVE.balanceOf(address(this))) revert Callback_MissingFunds(); - - // Validate that the callback received the correct amount of base tokens as a refund - // As this is a single-use contract and we control the minting of bAssets, bAsset balance is 0 prior - if (refund_ > bAsset.balanceOf(address(this))) revert Callback_MissingFunds(); - - // Set the auction as complete - auctionComplete = true; - - //// Step 1: Burn any refunded bAsset tokens //// - // Unlock BPOOL transfers - BPOOL.setTransferLock(false); - - // Burn any refunded bAsset tokens that were sent from the auction house - Transfer.transfer(bAsset, address(BPOOL), refund_, false); - BPOOL.burnAllBAssetsInContract(); - - //// Step 2: Ensure the pool is at the correct price //// - // Since there is no bAsset liquidity deployed yet, - // External LPs can move the current price of the pool. - // We move it back to the target active tick to ensure - // the pool is at the correct price. - { - IUniswapV3Pool pool = BPOOL.pool(); - - // Current price of the pool - (uint160 currentSqrtPrice,,,,,,) = pool.slot0(); - - // Get the target sqrt price from the target tick - uint160 targetSqrtPrice = TickMath.getSqrtRatioAtTick(poolTargetTick); - - // We assume there are no circulating bAssets that could be provided as liquidity yet. - // Therefore, there are three cases: - // 1. The current price is above the target price - if (currentSqrtPrice > targetSqrtPrice) { - // In this case, an external LP has provided reserve liquidity above our range. - // We can sell bAssets into this liquidity and the external LP will effectively be - // bAssets at a premium to the initial price of the pool. - // This does not affect the solvency of the system since the reserves received - // are greater than the tokens minted, but it may cause the system to be - // initialized with a surplus, which would allow for an immediate bump or snipe. - // - // We want to swap out all of the reserves currently in the pool above the target price for bAssets. - // We just use the total balance in the pool because the price limit will prevent buying lower. - int256 amount1Out = -int256(RESERVE.balanceOf(address(pool))); - - // If there is no liquidity in the pool, this ensures that the swap will suceed - if (amount1Out == 0) amount1Out = -1; - - pool.swap( - address(this), // recipient - true, // zeroToOne, swapping token0 (bAsset) for token1 (reserve) so this is true - amount1Out, // amountSpecified, positive is exactIn, negative is exactOut - targetSqrtPrice, // sqrtPriceLimitX96 - abi.encode(1) // data, case 1 - ); - } - // 2. The current price is below the target price - else if (currentSqrtPrice < targetSqrtPrice) { - // Swap 1 wei of token1 (reserve) for token0 (bAsset) with a limit at the targetSqrtPrice - // There are no bAssets in the pool, so we receive none. Because of this, - // we don't end up paying any reserves either, but the price of the pool is shifted. - pool.swap( - address(this), // recipient - false, // zeroToOne, swapping token1 (reserve) for token0 (bAsset) so this is false - int256(1), // amountSpecified, positive is exactIn, negative is exactOut - targetSqrtPrice, // sqrtPriceLimitX96 - abi.encode(2) // data, case 2 - ); - } - // 3. The current price is at the target price. - // If so, we don't need to do anything. - - // We don't need to track any of these amounts because the liquidity deployment and - // will handle any extra reserves and the solvency check ensures that the system - // can support the supply. - - // Check that the price is now at the target price - (currentSqrtPrice,,,,,,) = pool.slot0(); - if (currentSqrtPrice != targetSqrtPrice) { - revert Callback_InvalidInitialization(); - } - } - - //// Step 3: Deploy liquidity to the Baseline pool //// - - // Calculate reserves to add to the pool - // Because we potentially extracted reserves from the pool in the previous step, - // we use the current balance minus the seller proceeds from the auction as - // the pool proceeds amount so that the surplus is provided to the pool. - // If no reserves were extracted, this will be the same amount as expected. - uint256 sellerProceeds = - proceeds_ * (ONE_HUNDRED_PERCENT - poolPercent) / ONE_HUNDRED_PERCENT; - - uint256 poolProceeds = RESERVE.balanceOf(address(this)) - sellerProceeds; - - // Approve spending of the reserve token - Transfer.approve(RESERVE, address(BPOOL), poolProceeds); - - // Add the configured percentage of the proceeds to the Floor range - uint256 floorReserves = poolProceeds * floorReservesPercent / ONE_HUNDRED_PERCENT; - BPOOL.addReservesTo(Range.FLOOR, floorReserves); - - // Add the remainder of the proceeds to the Anchor range - BPOOL.addReservesTo(Range.ANCHOR, poolProceeds - floorReserves); - - // Ensure that there are no dangling approvals - Transfer.approve(RESERVE, address(BPOOL), 0); - - // Add proportional liquidity to the Discovery range. - // Only the anchor range is used, otherwise the liquidity would be too thick. - // The anchor range is guranteed to have a tick spacing width - // and to have reserves of at least 1% of the proceeds. - BPOOL.addLiquidityTo(Range.DISCOVERY, BPOOL.getLiquidity(Range.ANCHOR) * 11 / 10); - - //// Step 4: Send remaining proceeds (and any excess reserves) to the recipient //// - Transfer.transfer(RESERVE, recipient, RESERVE.balanceOf(address(this)), false); - - //// Step 5: Verify Solvency //// - { - Position memory floor = BPOOL.getPosition(Range.FLOOR); - Position memory anchor = BPOOL.getPosition(Range.ANCHOR); - Position memory discovery = BPOOL.getPosition(Range.DISCOVERY); - - // Calculate the debt capacity at the floor range - uint256 debtCapacity = BPOOL.getCapacityForReserves( - floor.sqrtPriceL, floor.sqrtPriceU, CREDT.totalCreditIssued() + LOOPS.totalDebt() - ); - - uint256 totalCapacity = - debtCapacity + floor.capacity + anchor.capacity + discovery.capacity; - // Includes collateralised supply - uint256 totalSpotSupply = - bAsset.totalSupply() - floor.bAssets - anchor.bAssets - discovery.bAssets; - - // verify the liquidity can support the intended supply - // we do not check for a surplus at this point to avoid a DoS attack vector - // during the onCreate callback, we check for a surplus and there shouldn't - // be one from this initialization at this point. - // any surplus reserves added to the pool by a 3rd party before - // the system is initialized will be snipable and effectively donated to the snipers - uint256 capacityRatio = totalCapacity.divWad(totalSpotSupply); - if (capacityRatio < 100e16) { - revert Callback_InvalidCapacityRatio(capacityRatio); - } - } - - // Lock BPOOL transfers to prevent any token interactions until the system is ready - BPOOL.setTransferLock(true); - - // Emit an event - { - (int24 floorTickLower,) = BPOOL.getTicks(Range.FLOOR); - (, int24 anchorTickUpper) = BPOOL.getTicks(Range.ANCHOR); - emit LiquidityDeployed( - floorTickLower, - anchorTickUpper, - BPOOL.getLiquidity(Range.FLOOR), - BPOOL.getLiquidity(Range.ANCHOR) - ); - } - } - - // ========== INTERNAL FUNCTIONS ========== // - - /// @notice Calculate the expected proceeds from the auction and how much will be deposited in the pool - /// @dev The proceeds sent to the onSettle callback function will exclude any protocol and referrer fees, so this calculation mimics the behaviour - /// - /// @param lotId_ Lot ID of the auction - /// @param auctionPrice_ Price of the auction - /// @param capacity_ Capacity of the auction - /// @return proceeds Expected proceeds from the auction - function _getExpectedProceeds( - uint96 lotId_, - uint256 auctionPrice_, - uint256 capacity_ - ) internal view returns (uint256) { - // Get the fees from the auction house - (,,, uint48 protocolFee, uint48 referrerFee) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); - - // Calculate the expected proceeds after fees - uint256 proceedsBeforeFees = (auctionPrice_ * capacity_) / (10 ** bAsset.decimals()); - return proceedsBeforeFees - (proceedsBeforeFees * protocolFee) / ONE_HUNDRED_PERCENT - - (proceedsBeforeFees * referrerFee) / ONE_HUNDRED_PERCENT; - } - - // ========== UNIV3 FUNCTIONS ========== // - - // Provide tokens when adjusting the pool price via a swap before deploying liquidity - function uniswapV3SwapCallback(int256 bAssetDelta_, int256, bytes calldata data_) external { - // Only the pool can call - address pool = address(BPOOL.pool()); - if (msg.sender != pool) revert Callback_Swap_InvalidCaller(); - - // Decode the data - (uint8 case_) = abi.decode(data_, (uint8)); - - // Handle the swap case - if (case_ == 1) { - // Mint the bAsset delta to the pool (if greater than 0) - if (bAssetDelta_ > 0) { - BPOOL.mint(pool, uint256(bAssetDelta_)); - } - } else if (case_ == 2) { - // Case 2: Swapped in 1 wei of reserve tokens - // We don't need to do anything here - } else { - revert Callback_Swap_InvalidCase(); - } - } -} +// /// @notice The case for the Uniswap V3 swap callback is invalid +// error Callback_Swap_InvalidCase(); + +// // ========== EVENTS ========== // + +// event LiquidityDeployed( +// int24 floorTickLower, int24 anchorTickUpper, uint128 floorLiquidity, uint128 anchorLiquidity +// ); + +// // ========== DATA STRUCTURES ========== // + +// /// @notice Data struct for the onCreate callback +// /// +// /// @param recipient The address to receive proceeds that do not go to the pool +// /// @param poolPercent The percentage of the proceeds to allocate to the pool, in basis points (1% = 100). The remainder will be sent to the `recipient`. +// /// @param floorReservesPercent The percentage of the pool proceeds to allocate to the floor range, in basis points (1% = 100). The remainder will be allocated to the anchor range. +// /// @param floorRangeGap The gap between the floor and anchor ranges, as a multiple of the pool tick spacing. +// /// @param anchorTickU The upper tick of the anchor range. Validated against the calculated upper bound of the anchor range. This is provided off-chain to prevent front-running. +// /// @param anchorTickWidth The width of the anchor tick range, as a multiple of the pool tick spacing. +// /// @param poolTargetTick The target tick for the pool. This is provided off-chain to prevent front-running. +// /// @param allowlistParams Additional parameters for an allowlist, passed to `__onCreate()` for further processing +// struct CreateData { +// address recipient; +// uint24 poolPercent; +// uint24 floorReservesPercent; +// int24 floorRangeGap; +// int24 anchorTickU; +// int24 anchorTickWidth; +// int24 poolTargetTick; +// bytes allowlistParams; +// } + +// // ========== CONSTANTS ========== // + +// /// @notice The minimum tick value +// int24 internal constant _MIN_TICK = -887_272; + +// /// @notice The maximum tick value +// int24 internal constant _MAX_TICK = 887_272; + +// /// @notice The value for 100% +// // solhint-disable-next-line private-vars-leading-underscore +// uint48 internal constant ONE_HUNDRED_PERCENT = 100e2; + +// /// @notice The tick spacing width of the discovery range +// int24 internal constant _DISCOVERY_TICK_SPACING_WIDTH = 350; + +// // ========== STATE VARIABLES ========== // + +// // Baseline Modules +// // solhint-disable var-name-mixedcase +// IBPOOLv1 public BPOOL; +// ICREDTv1 public CREDT; +// ILOOPSv1 public LOOPS; + +// // Pool variables +// ERC20 public immutable RESERVE; +// // solhint-enable var-name-mixedcase +// ERC20 public bAsset; + +// // Axis Auction Variables + +// /// @notice Lot ID of the auction for the baseline market. This callback only supports one lot. +// /// @dev This value is initialised with the uint96 max value to indicate that it has not been set yet. +// uint96 public lotId; + +// /// @notice Indicates whether the auction is complete +// /// @dev This is used to prevent the callback from being called multiple times. It is set in the `onSettle()` callback. +// bool public auctionComplete; + +// /// @notice The percentage of the proceeds to allocate to the pool +// /// @dev This value is set in the `onCreate()` callback. +// uint24 public poolPercent; + +// /// @notice The percentage of the proceeds to allocate to the floor range +// /// @dev This value is set in the `onCreate()` callback. +// uint24 public floorReservesPercent; + +// /// @notice The address to receive proceeds that do not go to the pool +// /// @dev This value is set in the `onCreate()` callback. +// address public recipient; + +// /// @notice The target tick for the pool +// /// @dev This value is set in the `onCreate()` callback. +// int24 public poolTargetTick; + +// // ========== CONSTRUCTOR ========== // + +// /// @notice Constructor for BaselineAxisLaunch +// /// +// /// @param auctionHouse_ The AuctionHouse the callback is paired with +// /// @param baselineKernel_ Address of the Baseline kernel +// /// @param reserve_ Address of the reserve token. This should match the quote token for the auction lot. +// /// @param owner_ Address of the owner of the contract. Must be the same as the eventual seller of the auction lot. +// constructor( +// address auctionHouse_, +// address baselineKernel_, +// address reserve_, +// address owner_ +// ) +// BaseCallback( +// auctionHouse_, +// Callbacks.Permissions({ +// onCreate: true, +// onCancel: true, +// onCurate: true, +// onPurchase: false, +// onBid: true, +// onSettle: true, +// receiveQuoteTokens: true, +// sendBaseTokens: true +// }) +// ) +// Policy(Kernel(baselineKernel_)) +// Owned(owner_) +// { +// // Set lot ID to max uint(96) initially so it doesn't reference a lot +// lotId = type(uint96).max; + +// // Set the reserve token +// RESERVE = ERC20(reserve_); +// } + +// // ========== POLICY FUNCTIONS ========== // + +// /// @inheritdoc Policy +// function configureDependencies() +// external +// override +// onlyKernel +// returns (BaselineKeycode[] memory dependencies) +// { +// BaselineKeycode bpool = toBaselineKeycode("BPOOL"); +// BaselineKeycode credt = toBaselineKeycode("CREDT"); +// BaselineKeycode loops = toBaselineKeycode("LOOPS"); + +// // Populate the dependencies array +// dependencies = new BaselineKeycode[](3); +// dependencies[0] = bpool; +// dependencies[1] = credt; +// dependencies[2] = loops; + +// // Set local values +// BPOOL = IBPOOLv1(getModuleAddress(bpool)); +// bAsset = ERC20(address(BPOOL)); +// CREDT = ICREDTv1(getModuleAddress(credt)); +// LOOPS = ILOOPSv1(getModuleAddress(loops)); + +// // Require that the BPOOL's reserve token be the same as the callback's reserve token +// if (address(BPOOL.reserve()) != address(RESERVE)) revert Callback_BPOOLReserveMismatch(); +// } + +// /// @inheritdoc Policy +// function requestPermissions() +// external +// view +// override +// onlyKernel +// returns (BaselinePermissions[] memory requests) +// { +// BaselineKeycode bpool = toBaselineKeycode("BPOOL"); + +// requests = new BaselinePermissions[](6); +// requests[0] = BaselinePermissions(bpool, BPOOL.addReservesTo.selector); +// requests[1] = BaselinePermissions(bpool, BPOOL.addLiquidityTo.selector); +// requests[2] = BaselinePermissions(bpool, BPOOL.burnAllBAssetsInContract.selector); +// requests[3] = BaselinePermissions(bpool, BPOOL.mint.selector); +// requests[4] = BaselinePermissions(bpool, BPOOL.setTicks.selector); +// requests[5] = BaselinePermissions(bpool, BPOOL.setTransferLock.selector); +// } + +// // ========== MODIFIERS ========== // + +// /// @notice Validates that the lot id matches the stored lot id +// modifier onlyValidLot( +// uint96 lotId_ +// ) { +// if (lotId_ != lotId) revert Callback_InvalidParams(); +// _; +// } + +// /// @notice Validates that the auction is not already settled or cancelled +// modifier onlyActiveLot() { +// if (auctionComplete) revert Callback_AlreadyComplete(); +// _; +// } + +// // ========== CALLBACK FUNCTIONS ========== // + +// // CALLBACK PERMISSIONS +// // onCreate: true +// // onCancel: true +// // onCurate: true +// // onPurchase: false +// // onBid: true +// // onSettle: true +// // receiveQuoteTokens: true +// // sendBaseTokens: true +// // Contract prefix should be: 11101111 = 0xEF + +// /// @inheritdoc BaseCallback +// /// @dev This function performs the following: +// /// - Performs validation +// /// - Sets the `lotId`, `percentReservesFloor`, `anchorTickWidth`, and `discoveryTickWidth` variables +// /// - Calls the allowlist callback +// /// - Performs a solvency check to ensure the pool can support the intended supply +// /// - Mints the required bAsset tokens to the AuctionHouse +// /// +// /// This function has the following assumptions: +// /// - Any Baseline credit allocations have been minted and allocated prior to auction creation (and this callback) +// /// +// /// This function reverts if: +// /// - `seller_` is not the owner +// /// - `baseToken_` is not the same as `bAsset` +// /// - `quoteToken_` is not the same as `RESERVE` +// /// - `baseToken_` is not lower than `quoteToken_` +// /// - `recipient` is the zero address +// /// - `lotId` is already set +// /// - The pool fee tier is not supported +// /// - The auction format is not supported +// /// - The auction is not prefunded +// /// - `CreateData.floorReservesPercent` is less than 10% or greater than 99% +// /// - `CreateData.poolPercent` is less than 10% or greater than 100% +// /// - `CreateData.floorRangeGap` is < 0 +// /// - `CreateData.anchorTickWidth` is < 10 or > 50 +// /// - `CreateData.anchorTickU` is not the same as the calculated value +// /// - `CreateData.poolTargetTick` is not >= anchorRangeLower and < anchorRangeUpper +// /// - Any of the tick ranges would exceed the tick bounds +// /// - The pool tick is less than the auction price (in terms of ticks) +// /// - The pool capacity is not sufficient to support the intended supply +// function _onCreate( +// uint96 lotId_, +// address seller_, +// address baseToken_, +// address quoteToken_, +// uint256 capacity_, +// bool prefund_, +// bytes calldata callbackData_ +// ) internal override { +// // Validate that the seller is the owner +// // Otherwise this single-use callback could be used by anyone +// if (seller_ != owner) { +// revert Callback_NotAuthorized(); +// } + +// // Validate the base token is the baseline token +// // and the quote token is the reserve +// if (baseToken_ != address(bAsset)) { +// revert Callback_Params_BAssetTokenMismatch(baseToken_, address(bAsset)); +// } +// if (quoteToken_ != address(RESERVE)) { +// revert Callback_Params_ReserveTokenMismatch(quoteToken_, address(RESERVE)); +// } +// // Ensure the base token is lower than the quote token +// if (address(bAsset) > address(RESERVE)) { +// revert Callback_BPOOLInvalidAddress(); +// } + +// // Validate that the lot ID is not already set +// if (lotId != type(uint96).max) revert Callback_InvalidParams(); + +// // Decode the provided callback data (must be correctly formatted even if not using parts of it) +// CreateData memory cbData = abi.decode(callbackData_, (CreateData)); + +// // Validate that the recipient is not the zero address +// if (cbData.recipient == address(0)) revert Callback_Params_InvalidRecipient(); + +// // Validate that the pool fee tier is supported +// // This callback only supports the 1% fee tier (tick spacing = 200) +// // as other fee tiers are not supported by the Baseline pool +// if (BPOOL.TICK_SPACING() != 200) revert Callback_Params_UnsupportedPoolFeeTier(); + +// // Validate that the floor range gap is at least 0 +// if (cbData.floorRangeGap < 0) revert Callback_Params_InvalidFloorRangeGap(); + +// // Validate that the anchor tick width is at least 10 tick spacing and at most 50 +// // Baseline supports only within this range +// if (cbData.anchorTickWidth < 10 || cbData.anchorTickWidth > 50) { +// revert Callback_Params_InvalidAnchorTickWidth(); +// } + +// // Validate that the floor reserves percent is between 10% and 90% +// // If the floor reserves are too low, it can render `MarketMaking.slide()` inoperable +// // If the floor reserves are too high, it can render `MarketMaking.sweep()` inoperable +// // as the anchor and discovery liquidity will be too thin +// if (cbData.floorReservesPercent < 10e2 || cbData.floorReservesPercent > 99e2) { +// revert Callback_Params_InvalidFloorReservesPercent(); +// } + +// // Validate that the pool percent is at least 10% and at most 100% +// if (cbData.poolPercent < 10e2 || cbData.poolPercent > 100e2) { +// revert Callback_Params_InvalidPoolPercent(); +// } + +// // Auction must be prefunded for batch auctions (which is the only type supported with this callback), +// // this can't fail because it's checked in the AH as well, but including for completeness +// if (!prefund_) revert Callback_Params_UnsupportedAuctionFormat(); + +// // Set the lot ID +// lotId = lotId_; + +// // Set the recipient +// recipient = cbData.recipient; + +// // Set the pool percent +// poolPercent = cbData.poolPercent; + +// // Set the floor reserves percent +// floorReservesPercent = cbData.floorReservesPercent; + +// // Only supports Fixed Price Batch Auctions initially +// { +// // Get the auction format +// AxisKeycode auctionFormat = keycodeFromVeecode( +// AxisModule(address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_))) +// .VEECODE() +// ); + +// if (fromAxisKeycode(auctionFormat) != bytes5("FPBA")) { +// revert Callback_Params_UnsupportedAuctionFormat(); +// } +// } + +// // This contract can be extended with an allowlist for the auction +// // Call a lower-level function where this information can be used +// // We do this before token interactions to conform to CEI +// __onCreate( +// lotId_, seller_, baseToken_, quoteToken_, capacity_, prefund_, cbData.allowlistParams +// ); + +// // Set the ticks for the Baseline pool initially with the following assumptions: +// // - The floor range is 1 tick spacing wide +// // - The anchor range is `anchorTickWidth` tick spacings wide, above the floor range +// // - The discovery range is `discoveryTickWidth` tick spacings wide, above the anchor range +// // - The anchor range contains the active tick +// // - The anchor range upper tick is the active tick rounded up to the nearest tick spacing +// // - The other range boundaries are calculated accordingly +// { +// // Check that the anchor tick range upper bound is the same +// // as the closest tick spacing boundary above the active tick on the BPOOL +// // We check this value against a parameter instead of reading +// // directly to avoid a situation where someone front-runs the +// // auction creation transaction and moves the active tick +// if (cbData.anchorTickU != BPOOL.getActiveTS()) { +// revert Callback_Params_InvalidAnchorTickUpper(); +// } +// int24 anchorRangeUpper = cbData.anchorTickU; + +// // Get the tick spacing from the pool +// int24 tickSpacing = BPOOL.TICK_SPACING(); + +// // Anchor range lower is the anchor tick width below the anchor range upper +// int24 anchorRangeLower = anchorRangeUpper - cbData.anchorTickWidth * tickSpacing; + +// // Validate that the pool target tick is within the anchor range +// // The `_onSettle()` function will perform swaps (if necessary) to move the pool tick to the target tick in order to mitigate manipulation. +// // The value must be in the anchor range and below the anchor upper tick (which is where the discovery range begins). +// if ( +// cbData.poolTargetTick < anchorRangeLower +// || cbData.poolTargetTick >= anchorRangeUpper +// ) { +// revert Callback_Params_InvalidPoolTargetTick(anchorRangeLower, anchorRangeUpper); +// } +// poolTargetTick = cbData.poolTargetTick; + +// // Set the anchor range +// BPOOL.setTicks(Range.ANCHOR, anchorRangeLower, anchorRangeUpper); + +// // Set the floor range +// // The creator can provide the `floorRangeGap` to space the floor range from the anchor range +// // If `floorRangeGap` is 0, the floor range will be directly below the anchor range +// // The floor range is one tick spacing wide +// int24 floorRangeUpper = anchorRangeLower - cbData.floorRangeGap * tickSpacing; +// int24 floorRangeLower = floorRangeUpper - tickSpacing; + +// BPOOL.setTicks(Range.FLOOR, floorRangeLower, floorRangeUpper); + +// // Set the discovery range +// int24 discoveryRangeUpper = +// anchorRangeUpper + tickSpacing * _DISCOVERY_TICK_SPACING_WIDTH; +// BPOOL.setTicks(Range.DISCOVERY, anchorRangeUpper, discoveryRangeUpper); + +// // If the floor range lower tick (or any other above it) is below the min tick, it will cause problems +// // If the discovery range upper tick (or any other below it) is above the max tick, it will cause problems +// if (floorRangeLower < _MIN_TICK || discoveryRangeUpper > _MAX_TICK) { +// revert Callback_Params_RangeOutOfBounds(); +// } +// } + +// // Perform a pre-check to make sure the setup can be valid +// // This avoids certain bad configurations that would lead to failed initializations +// // Specifically, we check that the pool can support the intended supply +// // factoring in the capacity, curator fee, and any additional spot or collateralized supply +// // that already exists. +// // We assume that the auction capacity will be completely filled. This can be guaranteed by +// // setting the minFillPercent to 100e2 on the auction. +// { +// // Calculate the initial circulating supply (including collateralized supply) +// uint256 initialCircSupply; +// { +// // Get the current supply values +// uint256 totalSupply = bAsset.totalSupply(); // can use totalSupply here since no bAssets are in the pool yet + +// // Calculate the maximum curator fee that can be paid +// (,, uint48 curatorFeePerc,,) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); +// uint256 curatorFee = (capacity_ * curatorFeePerc) / ONE_HUNDRED_PERCENT; + +// // Capacity and curator fee have not yet been minted, so we add those +// // Collateralized supply is already minted and included in total supply, so we do not need to add it +// initialCircSupply = totalSupply + capacity_ + curatorFee; +// } + +// // Calculate the initial capacity of the pool based on the ticks set and the expected proceeds to deposit in the pool +// uint256 initialCapacity; +// { +// // Get the fixed price from the auction module +// // This value is in the number of reserve tokens per baseline token +// uint256 auctionPrice; +// { +// auctionPrice = IFixedPriceBatch( +// address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_)) +// ).getAuctionData(lotId_).price; +// } + +// // Get the active tick from the pool and confirm it is >= the auction price corresponds to +// { +// // We do this to avoid a situation where buyers are disincentivized to bid on the auction +// // Pool price is number of token1 (reserve) per token0 (bAsset), which is what we want, but it needs to be squared +// (, int24 activeTick,,,,,) = BPOOL.pool().slot0(); + +// // Calculate the tick for the auction price +// // `getSqrtPriceX96` handles token ordering +// // The resulting tick will incorporate any differences in decimals between the tokens +// uint160 sqrtPriceX96 = SqrtPriceMath.getSqrtPriceX96( +// address(RESERVE), address(bAsset), auctionPrice, 10 ** bAsset.decimals() +// ); +// int24 auctionTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); + +// // Verify that the active tick is at least the auction tick +// if (activeTick < auctionTick) { +// revert Callback_PoolLessThanAuctionPrice(activeTick, auctionTick); +// } +// } + +// uint256 poolProceeds = ( +// _getExpectedProceeds(lotId_, capacity_, auctionPrice) * poolPercent +// ) / ONE_HUNDRED_PERCENT; + +// // Calculate the expected reserves for the floor and anchor ranges +// uint256 floorReserves = (poolProceeds * floorReservesPercent) / ONE_HUNDRED_PERCENT; +// uint256 anchorReserves = poolProceeds - floorReserves; + +// // Calculate the expected capacity of the pool +// // Skip discovery range since no reserves will be deposited in it +// Position memory floor = BPOOL.getPosition(Range.FLOOR); +// Position memory anchor = BPOOL.getPosition(Range.ANCHOR); + +// uint256 floorCapacity = +// BPOOL.getCapacityForReserves(floor.sqrtPriceL, floor.sqrtPriceU, floorReserves); +// uint256 anchorCapacity = BPOOL.getCapacityForReserves( +// anchor.sqrtPriceL, anchor.sqrtPriceU, anchorReserves +// ); + +// // Calculate the debt capacity at the floor range +// uint256 debtCapacity = BPOOL.getCapacityForReserves( +// floor.sqrtPriceL, +// floor.sqrtPriceU, +// CREDT.totalCreditIssued() + LOOPS.totalDebt() +// ); + +// // Calculate the total initial capacity of the pool +// initialCapacity = debtCapacity + floorCapacity + anchorCapacity; +// } + +// // Verify the liquidity can support the intended supply +// // and that there is no significant initial surplus +// // +// // If the solvency check is failing, it can be resolved by adjusting the following: +// // - auction price (via the auction fixed price) +// // - system liquidity (via the pool allocation and floor reserves allocation) +// uint256 capacityRatio = initialCapacity.divWad(initialCircSupply); +// if (capacityRatio < 100e16 || capacityRatio > 102e16) { +// revert Callback_InvalidCapacityRatio(capacityRatio); +// } +// } + +// // Unlock BPOOL transfers +// BPOOL.setTransferLock(false); + +// // Mint the capacity of baseline tokens to the auction house to prefund the auction +// BPOOL.mint(msg.sender, capacity_); + +// // Lock BPOOL transfers +// // This is to prevent any transfers of bAssets until the auction is settled +// // The BPOOL will need to be manually unlocked prior to the auction being cancelled or settled +// BPOOL.setTransferLock(true); +// } + +// /// @notice Override this function to implement allowlist functionality +// function __onCreate( +// uint96 lotId_, +// address seller_, +// address baseToken_, +// address quoteToken_, +// uint256 capacity_, +// bool prefund_, +// bytes memory allowlistData_ +// ) internal virtual {} + +// /// @inheritdoc BaseCallback +// /// @dev This function performs the following: +// /// - Performs validation +// /// - Burns the refunded bAsset tokens +// /// +// /// This function has the following assumptions: +// /// - BaseCallback has already validated the lot ID +// /// - The AuctionHouse has already sent the correct amount of bAsset tokens +// /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of BPOOL tokens from the AuctionHouse to the callback +// /// +// /// This function reverts if: +// /// - `lotId_` is not the same as the stored `lotId` +// /// - The auction is already complete +// /// - Sufficient quantity of `bAsset` have not been sent to the callback +// function _onCancel( +// uint96 lotId_, +// uint256 refund_, +// bool, +// bytes calldata +// ) internal override onlyValidLot(lotId_) onlyActiveLot { +// // Burn any refunded tokens (all auctions are prefunded) +// // Verify that the callback received the correct amount of bAsset tokens +// if (bAsset.balanceOf(address(this)) < refund_) revert Callback_MissingFunds(); + +// // Set the auction lot to be cancelled +// auctionComplete = true; + +// // Unlock BPOOL transfers +// BPOOL.setTransferLock(false); + +// // Send tokens to BPOOL and then burn +// Transfer.transfer(bAsset, address(BPOOL), refund_, false); +// BPOOL.burnAllBAssetsInContract(); + +// // Lock BPOOL transfers +// BPOOL.setTransferLock(true); +// } + +// /// @inheritdoc BaseCallback +// /// @dev This function performs the following: +// /// - Performs validation +// /// +// /// This function has the following assumptions: +// /// - BaseCallback has already validated the lot ID +// /// +// /// This function reverts if: +// /// - `lotId_` is not the same as the stored `lotId` +// /// - The curator fee is non-zero +// function _onCurate( +// uint96 lotId_, +// uint256 curatorFee_, +// bool, +// bytes calldata +// ) internal override onlyValidLot(lotId_) onlyActiveLot { +// // Mint tokens for curator fee if it's not zero +// if (curatorFee_ > 0) { +// // Unlock BPOOL transfers +// BPOOL.setTransferLock(false); + +// BPOOL.mint(msg.sender, curatorFee_); + +// // Lock BPOOL transfers +// BPOOL.setTransferLock(true); +// } +// } + +// /// @inheritdoc BaseCallback +// /// @dev Not implemented since atomic auctions are not supported +// function _onPurchase( +// uint96, +// address, +// uint256, +// uint256, +// bool, +// bytes calldata +// ) internal pure override { +// revert Callback_NotImplemented(); +// } + +// /// @inheritdoc BaseCallback +// /// @dev No logic is needed for this function here, but it can be overridden by a lower-level contract to provide allowlist functionality +// function _onBid( +// uint96 lotId_, +// uint64 bidId, +// address buyer_, +// uint256 amount_, +// bytes calldata callbackData_ +// ) internal virtual override {} + +// /// @inheritdoc BaseCallback +// /// @dev This function performs the following: +// /// - Performs validation +// /// - Sets the auction as complete +// /// - Burns any refunded bAsset tokens +// /// - Ensures that the pool is at the correct price +// /// - Deploys reserves and liquidity into the Baseline pool +// /// - Performs a solvency check to ensure the pool can support the supply +// /// - Transfers any remaining proceeds (reserves) to the recipient +// /// +// /// Next steps: +// /// - Activate the market making and credit facility policies in the Baseline stack, which cannot be enabled before the auction is settled and the pool is initialized +// /// +// /// This function has the following assumptions: +// /// - BaseCallback has already validated the lot ID +// /// - The AuctionHouse has already sent the correct amount of quote tokens (proceeds) +// /// - The AuctionHouse has already sent the correct amount of refunded base tokens +// /// - The AuctionHouse is pre-funded, so does not require additional base tokens (bAssets) to be supplied +// /// - No new Baseline credit allocations have been made since the auction was created (and `onCreate` was called) +// /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of refunded BPOOL tokens from the AuctionHouse to the callback +// /// +// /// This function reverts if: +// /// - `lotId_` is not the same as the stored `lotId` +// /// - The auction is already complete +// /// - The reported proceeds received are less than the reserve balance +// /// - The reported refund received is less than the bAsset balance +// /// - The pool price is not at the target price +// /// - The pool capacity is not sufficient to support the intended supply +// /// +// /// Note that while the solvency check in both `onCreate` and `onSettle` are consistent, if the auction is not fully subscribed (and hence there is a refund), it can cause the solvency check to fail in `onSettle`. +// function _onSettle( +// uint96 lotId_, +// uint256 proceeds_, +// uint256 refund_, +// bytes calldata +// ) internal virtual override onlyValidLot(lotId_) onlyActiveLot { +// // Validate that the callback received the correct amount of proceeds +// // As this is a single-use contract, reserve balance is likely 0 prior, but extra funds will not affect it +// if (proceeds_ > RESERVE.balanceOf(address(this))) revert Callback_MissingFunds(); + +// // Validate that the callback received the correct amount of base tokens as a refund +// // As this is a single-use contract and we control the minting of bAssets, bAsset balance is 0 prior +// if (refund_ > bAsset.balanceOf(address(this))) revert Callback_MissingFunds(); + +// // Set the auction as complete +// auctionComplete = true; + +// //// Step 1: Burn any refunded bAsset tokens //// +// // Unlock BPOOL transfers +// BPOOL.setTransferLock(false); + +// // Burn any refunded bAsset tokens that were sent from the auction house +// Transfer.transfer(bAsset, address(BPOOL), refund_, false); +// BPOOL.burnAllBAssetsInContract(); + +// //// Step 2: Ensure the pool is at the correct price //// +// // Since there is no bAsset liquidity deployed yet, +// // External LPs can move the current price of the pool. +// // We move it back to the target active tick to ensure +// // the pool is at the correct price. +// { +// IUniswapV3Pool pool = BPOOL.pool(); + +// // Current price of the pool +// (uint160 currentSqrtPrice,,,,,,) = pool.slot0(); + +// // Get the target sqrt price from the target tick +// uint160 targetSqrtPrice = TickMath.getSqrtRatioAtTick(poolTargetTick); + +// // We assume there are no circulating bAssets that could be provided as liquidity yet. +// // Therefore, there are three cases: +// // 1. The current price is above the target price +// if (currentSqrtPrice > targetSqrtPrice) { +// // In this case, an external LP has provided reserve liquidity above our range. +// // We can sell bAssets into this liquidity and the external LP will effectively be +// // bAssets at a premium to the initial price of the pool. +// // This does not affect the solvency of the system since the reserves received +// // are greater than the tokens minted, but it may cause the system to be +// // initialized with a surplus, which would allow for an immediate bump or snipe. +// // +// // We want to swap out all of the reserves currently in the pool above the target price for bAssets. +// // We just use the total balance in the pool because the price limit will prevent buying lower. +// int256 amount1Out = -int256(RESERVE.balanceOf(address(pool))); + +// // If there is no liquidity in the pool, this ensures that the swap will suceed +// if (amount1Out == 0) amount1Out = -1; + +// pool.swap( +// address(this), // recipient +// true, // zeroToOne, swapping token0 (bAsset) for token1 (reserve) so this is true +// amount1Out, // amountSpecified, positive is exactIn, negative is exactOut +// targetSqrtPrice, // sqrtPriceLimitX96 +// abi.encode(1) // data, case 1 +// ); +// } +// // 2. The current price is below the target price +// else if (currentSqrtPrice < targetSqrtPrice) { +// // Swap 1 wei of token1 (reserve) for token0 (bAsset) with a limit at the targetSqrtPrice +// // There are no bAssets in the pool, so we receive none. Because of this, +// // we don't end up paying any reserves either, but the price of the pool is shifted. +// pool.swap( +// address(this), // recipient +// false, // zeroToOne, swapping token1 (reserve) for token0 (bAsset) so this is false +// int256(1), // amountSpecified, positive is exactIn, negative is exactOut +// targetSqrtPrice, // sqrtPriceLimitX96 +// abi.encode(2) // data, case 2 +// ); +// } +// // 3. The current price is at the target price. +// // If so, we don't need to do anything. + +// // We don't need to track any of these amounts because the liquidity deployment and +// // will handle any extra reserves and the solvency check ensures that the system +// // can support the supply. + +// // Check that the price is now at the target price +// (currentSqrtPrice,,,,,,) = pool.slot0(); +// if (currentSqrtPrice != targetSqrtPrice) { +// revert Callback_InvalidInitialization(); +// } +// } + +// //// Step 3: Deploy liquidity to the Baseline pool //// + +// // Calculate reserves to add to the pool +// // Because we potentially extracted reserves from the pool in the previous step, +// // we use the current balance minus the seller proceeds from the auction as +// // the pool proceeds amount so that the surplus is provided to the pool. +// // If no reserves were extracted, this will be the same amount as expected. +// uint256 sellerProceeds = +// proceeds_ * (ONE_HUNDRED_PERCENT - poolPercent) / ONE_HUNDRED_PERCENT; + +// uint256 poolProceeds = RESERVE.balanceOf(address(this)) - sellerProceeds; + +// // Approve spending of the reserve token +// Transfer.approve(RESERVE, address(BPOOL), poolProceeds); + +// // Add the configured percentage of the proceeds to the Floor range +// uint256 floorReserves = poolProceeds * floorReservesPercent / ONE_HUNDRED_PERCENT; +// BPOOL.addReservesTo(Range.FLOOR, floorReserves); + +// // Add the remainder of the proceeds to the Anchor range +// BPOOL.addReservesTo(Range.ANCHOR, poolProceeds - floorReserves); + +// // Ensure that there are no dangling approvals +// Transfer.approve(RESERVE, address(BPOOL), 0); + +// // Add proportional liquidity to the Discovery range. +// // Only the anchor range is used, otherwise the liquidity would be too thick. +// // The anchor range is guranteed to have a tick spacing width +// // and to have reserves of at least 1% of the proceeds. +// BPOOL.addLiquidityTo(Range.DISCOVERY, BPOOL.getLiquidity(Range.ANCHOR) * 11 / 10); + +// //// Step 4: Send remaining proceeds (and any excess reserves) to the recipient //// +// Transfer.transfer(RESERVE, recipient, RESERVE.balanceOf(address(this)), false); + +// //// Step 5: Verify Solvency //// +// { +// Position memory floor = BPOOL.getPosition(Range.FLOOR); +// Position memory anchor = BPOOL.getPosition(Range.ANCHOR); +// Position memory discovery = BPOOL.getPosition(Range.DISCOVERY); + +// // Calculate the debt capacity at the floor range +// uint256 debtCapacity = BPOOL.getCapacityForReserves( +// floor.sqrtPriceL, floor.sqrtPriceU, CREDT.totalCreditIssued() + LOOPS.totalDebt() +// ); + +// uint256 totalCapacity = +// debtCapacity + floor.capacity + anchor.capacity + discovery.capacity; +// // Includes collateralised supply +// uint256 totalSpotSupply = +// bAsset.totalSupply() - floor.bAssets - anchor.bAssets - discovery.bAssets; + +// // verify the liquidity can support the intended supply +// // we do not check for a surplus at this point to avoid a DoS attack vector +// // during the onCreate callback, we check for a surplus and there shouldn't +// // be one from this initialization at this point. +// // any surplus reserves added to the pool by a 3rd party before +// // the system is initialized will be snipable and effectively donated to the snipers +// uint256 capacityRatio = totalCapacity.divWad(totalSpotSupply); +// if (capacityRatio < 100e16) { +// revert Callback_InvalidCapacityRatio(capacityRatio); +// } +// } + +// // Lock BPOOL transfers to prevent any token interactions until the system is ready +// BPOOL.setTransferLock(true); + +// // Emit an event +// { +// (int24 floorTickLower,) = BPOOL.getTicks(Range.FLOOR); +// (, int24 anchorTickUpper) = BPOOL.getTicks(Range.ANCHOR); +// emit LiquidityDeployed( +// floorTickLower, +// anchorTickUpper, +// BPOOL.getLiquidity(Range.FLOOR), +// BPOOL.getLiquidity(Range.ANCHOR) +// ); +// } +// } + +// // ========== INTERNAL FUNCTIONS ========== // + +// /// @notice Calculate the expected proceeds from the auction and how much will be deposited in the pool +// /// @dev The proceeds sent to the onSettle callback function will exclude any protocol and referrer fees, so this calculation mimics the behaviour +// /// +// /// @param lotId_ Lot ID of the auction +// /// @param auctionPrice_ Price of the auction +// /// @param capacity_ Capacity of the auction +// /// @return proceeds Expected proceeds from the auction +// function _getExpectedProceeds( +// uint96 lotId_, +// uint256 auctionPrice_, +// uint256 capacity_ +// ) internal view returns (uint256) { +// // Get the fees from the auction house +// (,,, uint48 protocolFee, uint48 referrerFee) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); + +// // Calculate the expected proceeds after fees +// uint256 proceedsBeforeFees = (auctionPrice_ * capacity_) / (10 ** bAsset.decimals()); +// return proceedsBeforeFees - (proceedsBeforeFees * protocolFee) / ONE_HUNDRED_PERCENT +// - (proceedsBeforeFees * referrerFee) / ONE_HUNDRED_PERCENT; +// } + +// // ========== UNIV3 FUNCTIONS ========== // + +// // Provide tokens when adjusting the pool price via a swap before deploying liquidity +// function uniswapV3SwapCallback(int256 bAssetDelta_, int256, bytes calldata data_) external { +// // Only the pool can call +// address pool = address(BPOOL.pool()); +// if (msg.sender != pool) revert Callback_Swap_InvalidCaller(); + +// // Decode the data +// (uint8 case_) = abi.decode(data_, (uint8)); + +// // Handle the swap case +// if (case_ == 1) { +// // Mint the bAsset delta to the pool (if greater than 0) +// if (bAssetDelta_ > 0) { +// BPOOL.mint(pool, uint256(bAssetDelta_)); +// } +// } else if (case_ == 2) { +// // Case 2: Swapped in 1 wei of reserve tokens +// // We don't need to do anything here +// } else { +// revert Callback_Swap_InvalidCase(); +// } +// } +// } diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol index c8e53561..bdf93f04 100644 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol +++ b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Test scaffolding import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; @@ -45,3 +45,4 @@ contract BaselineAllocatedAllowlistTest is BaselineAxisLaunchTest { _; } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol index 9793e385..f14e2e48 100644 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol +++ b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -245,3 +245,4 @@ contract BaselineAllocatedAllowlistOnBidTest is BaselineAllocatedAllowlistTest { assertEq(BALwithAllocatedAllowlist(address(_dtl)).buyerSpent(_BUYER), 5e18, "buyer spent"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol index 462244c6..3edf9fb5 100644 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -66,3 +66,4 @@ contract BaselineAllocatedAllowlistOnCreateTest is BaselineAllocatedAllowlistTes assertEq(BALwithAllocatedAllowlist(address(_dtl)).merkleRoot(), _MERKLE_ROOT, "merkle root"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol index c318193e..a321c51f 100644 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol +++ b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; import {BALwithAllocatedAllowlist} from @@ -98,3 +98,4 @@ contract BaselineAllocatedAllowlistSetMerkleRootTest is BaselineAllocatedAllowli ); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol index 369e170a..87f8f15f 100644 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol +++ b/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Test scaffolding import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; @@ -45,3 +45,4 @@ contract BaselineAllowlistTest is BaselineAxisLaunchTest { _; } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol index 235a85a8..29447f25 100644 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol +++ b/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -120,3 +120,4 @@ contract BaselineAllowlistOnBidTest is BaselineAllowlistTest { // Does not revert } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol index 5204e985..86cfd7b0 100644 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -66,3 +66,4 @@ contract BaselineAllowlistOnCreateTest is BaselineAllowlistTest { assertEq(BALwithAllowlist(address(_dtl)).merkleRoot(), _MERKLE_ROOT, "merkle root"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol index 0486005f..e0d5d15b 100644 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol +++ b/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; import {BALwithAllowlist} from @@ -94,3 +94,4 @@ contract BaselineAllowlistSetMerkleRootTest is BaselineAllowlistTest { assertEq(BALwithAllowlist(address(_dtl)).merkleRoot(), _NEW_MERKLE_ROOT, "merkle root"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol b/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol index d8bb5787..7dd36bdb 100644 --- a/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol +++ b/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; import {Kernel, Keycode, toKeycode, Policy, Permissions} from "@baseline/Kernel.sol"; @@ -58,3 +58,4 @@ contract BPOOLMinter is Policy, Owned { CREDT.updateCreditAccount(user_, amount_, debt, block.timestamp + days_ * 1 days); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol b/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol index dcd1160c..08bf1c2f 100644 --- a/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol +++ b/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Test scaffolding import {Test} from "@forge-std-1.9.1/Test.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; @@ -759,3 +759,4 @@ abstract contract BaselineAxisLaunchTest is Test, Permit2User, WithSalts, TestCo ); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol index 30674e5e..c2192e1e 100644 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol +++ b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Test scaffolding import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; @@ -44,3 +44,4 @@ contract BaselineCappedAllowlistTest is BaselineAxisLaunchTest { _; } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol index b8bf96f1..ee282419 100644 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol +++ b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -208,3 +208,4 @@ contract BaselineCappedAllowlistOnBidTest is BaselineCappedAllowlistTest { assertEq(BALwithCappedAllowlist(address(_dtl)).buyerSpent(_BUYER), 5e18, "buyer spent"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol index dfcb8260..ecfa8901 100644 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -86,3 +86,4 @@ contract BaselineCappedAllowlistOnCreateTest is BaselineCappedAllowlistTest { assertEq(BALwithCappedAllowlist(address(_dtl)).buyerLimit(), _BUYER_LIMIT, "buyer limit"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol index e2e8df9a..c2689855 100644 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol +++ b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; import {BALwithCappedAllowlist} from @@ -98,3 +98,4 @@ contract BaselineCappedAllowlistSetMerkleRootTest is BaselineCappedAllowlistTest ); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/MockBlast.sol b/test/callbacks/liquidity/BaselineV2/MockBlast.sol index 9f25d088..e3352b25 100644 --- a/test/callbacks/liquidity/BaselineV2/MockBlast.sol +++ b/test/callbacks/liquidity/BaselineV2/MockBlast.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {YieldMode, GasMode} from "@baseline/utils/IBlast.sol"; /// @dev Implements the minimum interface required for BlastClaimer to interact with this contract. @@ -9,3 +9,4 @@ contract MockBlast { // Do nothing } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol index ffd04eda..8b34b12c 100644 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol +++ b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* // Test scaffolding import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; @@ -58,3 +58,4 @@ contract BaselineTokenAllowlistTest is BaselineAxisLaunchTest { _; } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol index 0f7ca91f..09df0d09 100644 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol +++ b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineTokenAllowlistTest} from "./BaselineTokenAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -72,3 +72,4 @@ contract BaselineTokenAllowlistOnBidTest is BaselineTokenAllowlistTest { _onBid(bidAmount); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol index 651ff12e..01cfc377 100644 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineTokenAllowlistTest} from "./BaselineTokenAllowlistTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -105,3 +105,4 @@ contract BaselineTokenAllowlistOnCreateTest is BaselineTokenAllowlistTest { assertEq(threshold, _TOKEN_THRESHOLD, "token threshold"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/onCancel.t.sol b/test/callbacks/liquidity/BaselineV2/onCancel.t.sol index cf8c3bc7..d04f2bb4 100644 --- a/test/callbacks/liquidity/BaselineV2/onCancel.t.sol +++ b/test/callbacks/liquidity/BaselineV2/onCancel.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -139,3 +139,4 @@ contract BaselineOnCancelTest is BaselineAxisLaunchTest { assertEq(_baseToken.locked(), true, "transfer lock"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/onCreate.t.sol index 8745b420..7a137ccc 100644 --- a/test/callbacks/liquidity/BaselineV2/onCreate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/onCreate.t.sol @@ -1,1394 +1,13 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; +/* +// Test scaffolding import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {BaselineAxisLaunch} from - "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; +import {BaselineAxisLaunch} from "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {Range} from "@baseline/modules/BPOOL.v1.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; - -import {console2} from "@forge-std-1.9.1/console2.sol"; - -contract BaselineOnCreateTest is BaselineAxisLaunchTest { - // ============ Modifiers ============ // - - // ============ Assertions ============ // - - function _expectTransferFrom() internal { - vm.expectRevert("TRANSFER_FROM_FAILED"); - } - - function _expectInvalidParams() internal { - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - } - - function _expectNotAuthorized() internal { - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - } - - function _assertBaseTokenBalances() internal view { - assertEq(_baseToken.balanceOf(_SELLER), 0, "seller balance"); - assertEq(_baseToken.balanceOf(_NOT_SELLER), 0, "not seller balance"); - assertEq(_baseToken.balanceOf(_dtlAddress), 0, "dtl balance"); - assertEq( - _baseToken.balanceOf(address(_auctionHouse)), - _scaleBaseTokenAmount(_LOT_CAPACITY), - "auction house balance" - ); - } - - // ============ Helper Functions ============ // - - /// @notice Returns the tick equivalent to the fixed price of the auction - /// @dev This function contains pre-calculated tick values, to prevent the implementation and tests using the same library. - /// - /// This function also handles a set number of decimal permutations. - function _getFixedPriceTick() internal view returns (int24) { - // Calculation source: https://blog.uniswap.org/uniswap-v3-math-primer#how-does-tick-and-tick-spacing-relate-to-sqrtpricex96 - - // Quote token is token1 - if (address(_quoteToken) > address(_baseToken)) { - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 18) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(3e18 * 2^192 / 1e18) - // = 1.3722720287e29 - // Tick = log((1.3722720287e29 / 2^96)^2) / log(1.0001) - // = 10,986.672184372 (rounded down) - // Price = 1.0001^10986 / (10^(18-18)) = 2.9997983618 - return 10_986; - } - - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 17) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(3e18 * 2^192 / 1e17) - // = 4.3395051823e29 - // Tick = log((4.3395051823e29 / 2^96)^2) / log(1.0001) - // = 34,013.6743980767 (rounded down) - // Price = 1.0001^34013 / (10^(18-17)) = 2.9997977008 - return 34_013; - } - - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 19) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(3e18 * 2^192 / 1e19) - // = 4.3395051799e28 - // Tick = log((4.3395051799e28 / 2^96)^2) / log(1.0001) - // = -12,040.3300194873 (rounded down) - // Price = 1.0001^-12041 / (10^(18-19)) = 2.9997990227 - return -12_041; - } - - revert("Unsupported decimal permutation"); - } - - // Quote token is token0 - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 18) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(1e18 * 2^192 / 3e18) - // = 4.574240096e28 - // Tick = log((4.574240096e28 / 2^96)^2) / log(1.0001) - // = -10,986.6721814657 (rounded down) - // Price = 1.0001^-10987 / (10^(18-18)) = 0.3333224068 = 0.3 base token per 1 quote token - return -10_987; - } - - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 17) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(1e17 * 2^192 / 3e18) - // = 1.4465017266e28 - // Tick = log((1.4465017266e28 / 2^96)^2) / log(1.0001) - // = -34,013.6743872434 (rounded down) - // Price = 1.0001^-34014 / (10^(17-18)) = 0.3333224803 = 0.3 base token per 1 quote token - return -34_014; - } - - if (_quoteTokenDecimals == 18 && _baseTokenDecimals == 19) { - // Fixed price = 3e18 - // SqrtPriceX96 = sqrt(1e19 * 2^192 / 3e18) - // = 1.4465017267e29 - // Tick = log((1.4465017267e29 / 2^96)^2) / log(1.0001) - // = 12,040.3300206416 (rounded down) - // Price = 1.0001^12040 / (10^(19-18)) = 0.3333223334 = 0.3 base token per 1 quote token - return 12_040; - } - - revert("Unsupported decimal permutation"); - } - - function _getPoolActiveTick() internal view returns (int24) { - (, int24 activeTick,,,,,) = _baseToken.pool().slot0(); - return activeTick; - } - - function _assertTicks( - int24 fixedPriceTick_ - ) internal view { - // Get the tick from the pool - int24 activeTick = _getPoolActiveTick(); - - assertEq(activeTick, fixedPriceTick_, "active tick"); - console2.log("Active tick: ", activeTick); - console2.log("Tick spacing: ", _tickSpacing); - - // Calculate the active tick with rounding - int24 anchorTickUpper = _roundToTickSpacingUp(fixedPriceTick_); - int24 anchorTickLower = anchorTickUpper - _createData.anchorTickWidth * _tickSpacing; - console2.log("Calculated anchor tick lower: ", anchorTickLower); - console2.log("Calculated anchor tick upper: ", anchorTickUpper); - - // Anchor range should be the width of anchorTickWidth * tick spacing - (int24 anchorTickLower_, int24 anchorTickUpper_) = _baseToken.getTicks(Range.ANCHOR); - assertEq(anchorTickLower_, anchorTickLower, "anchor tick lower"); - assertEq(anchorTickUpper_, anchorTickUpper, "anchor tick upper"); - - // Active tick should be within the anchor range - assertGt(fixedPriceTick_, anchorTickLower_, "active tick > anchor tick lower"); - assertLe(fixedPriceTick_, anchorTickUpper_, "active tick <= anchor tick upper"); - - // Floor range should be the width of the tick spacing and below the anchor range - int24 floorTickUpper_ = anchorTickLower_ - _floorRangeGap * _tickSpacing; - int24 floorTickLower_ = floorTickUpper_ - _tickSpacing; - - (int24 floorTickLower, int24 floorTickUpper) = _baseToken.getTicks(Range.FLOOR); - assertEq(floorTickUpper, floorTickUpper_, "floor tick upper"); - assertEq(floorTickLower, floorTickLower_, "floor tick lower"); - - // Discovery range should be the width of discoveryTickWidth * tick spacing and above the active tick - (int24 discoveryTickLower, int24 discoveryTickUpper) = _baseToken.getTicks(Range.DISCOVERY); - assertEq(discoveryTickLower, anchorTickUpper_, "discovery tick lower"); - assertEq( - discoveryTickUpper, - anchorTickUpper_ + _DISCOVERY_TICK_WIDTH * _tickSpacing, - "discovery tick upper" - ); - } - - // ============ Tests ============ // - - // [X] when the callback data is incorrect - // [X] it reverts - // [X] when the seller is not the owner - // [X] it reverts - // [X] when the callback is not called by the auction house - // [X] it reverts - // [X] when the lot has already been registered - // [X] it reverts - // [X] when the base token is not the BPOOL - // [X] it reverts - // [X] when the quote token is not the reserve - // [X] it reverts - // [X] when the base token is higher than the reserve token - // [X] it reverts - // [X] when the recipient is the zero address - // [X] it reverts - // [X] when the poolPercent is < 1% - // [X] it reverts - // [X] when the poolPercent is > 100% - // [X] it reverts - // [X] when the floorReservesPercent is not between 10% and 99% - // [X] it reverts - // [X] when the anchorTickWidth is < 10 - // [X] it reverts - // [X] when the auction format is not FPB - // [X] it reverts - // [X] when the auction is not prefunded - // [X] it reverts - // [X] when the floor reserves are too low - // [X] it reverts due to the solvency check - // [X] when the floor reserves are too high - // [X] it reverts due to the solvency check - // [X] when the pool percent is too low - // [X] it reverts due to the solvency check - // [X] when the pool percent is too high - // [X] it reverts due to the solvency check - // [X] when the floorReservesPercent is 10-99% - // [X] it correctly records the allocation - // [X] when the fee tier is not 10000 (1%) - // [X] it reverts - // [X] when the anchorTickU parameter does not equal the calculated value - // [X] it reverts - // [X] when the pool price is < the auction price - // [X] it reverts - // [X] when the pool price is >= the auction price - // [X] it succeeds - // [X] when the auction fixed price is very high - // [X] it handles the active tick correctly - // [X] when the auction fixed price is very low - // [X] it handles the active tick correctly - // [X] when the quote token decimals are higher than the base token decimals - // [X] it handles it correctly - // [X] when the quote token decimals are lower than the base token decimals - // [X] it handles it correctly - // [X] when there is a gap specified between the floor range and anchor range - // [X] when the floor range gap is below 0 - // [X] it reverts - // [X] when the floor range is calculated to be below the minimum tick - // [X] it reverts - // [X] it sets the ranges correctly - // [X] when the anchorTickWidth is small - // [X] it correctly sets the anchor ticks to not overlap with the other ranges - // [X] when the anchorTickWidth is less than 10 - // [X] it reverts - // [X] when the anchorTickWidth is greater than 50 - // [X] it reverts - // [X] when the activeTick and anchorTickWidth results in an overflow - // [X] it reverts - // [X] when the activeTick and anchorTickWidth results in an underflow - // [X] it reverts - // [X] when the activeTick and discoveryTickWidth results in an overflow - // [X] it reverts - // [X] when the activeTick and discoveryTickWidth results in an underflow - // [X] it reverts - // [X] given the protocol fee is set - // [X] given the protocol fee would result in a solvency check failure - // [X] it reverts - // [X] it correctly performs the solvency check - // [X] when the referrer fee is set - // [X] when the referrer fee would result in a solvency check failure - // [X] it reverts - // [X] it correctly performs the solvency check - // [X] when the pool target tick is below the anchor lower tick - // [X] it reverts - // [X] when the pool target tick is above the anchor upper tick - // [X] it reverts - // [X] it transfers the base token to the auction house, updates circulating supply, sets the state variables, initializes the pool and sets the tick ranges - - function test_callbackDataIncorrect_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - vm.expectRevert(); - - // Perform the call - vm.prank(address(_auctionHouse)); - _dtl.onCreate( - _lotId, - _SELLER, - address(_baseToken), - address(_quoteToken), - _LOT_CAPACITY, - true, - abi.encode(uint256(10), uint256(20)) - ); - } - - function test_sellerNotOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(_OWNER); - } - - function test_notAuctionHouse_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - _expectNotAuthorized(); - - // Perform the call - _dtl.onCreate( - _lotId, - _SELLER, - address(_baseToken), - address(_quoteToken), - _LOT_CAPACITY, - true, - abi.encode(_createData) - ); - } - - function test_lotAlreadyRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform callback - _onCreate(); - - // Expect revert - _expectInvalidParams(); - - // Perform the callback again - _onCreate(); - } - - function test_baseTokenNotBPool_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_BAssetTokenMismatch.selector, - address(_quoteToken), - address(_baseToken) - ); - vm.expectRevert(err); - - // Perform the call - vm.prank(address(_auctionHouse)); - _dtl.onCreate( - _lotId, - _SELLER, - address(_quoteToken), // Will revert as the quote token != BPOOL - address(_quoteToken), - _LOT_CAPACITY, - true, - abi.encode(_createData) - ); - } - - function test_quoteTokenNotReserve_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_ReserveTokenMismatch.selector, - address(_baseToken), - address(_quoteToken) - ); - vm.expectRevert(err); - - // Perform the call - vm.prank(address(_auctionHouse)); - _dtl.onCreate( - _lotId, - _SELLER, - address(_baseToken), - address(_baseToken), // Will revert as the base token != RESERVE - _LOT_CAPACITY, - true, - abi.encode(_createData) - ); - } - - function test_floorReservesPercent_belowMin_reverts( - uint24 floorReservesPercent_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - uint24 floorReservesPercent = uint24(bound(floorReservesPercent_, 0, 10e2 - 1)); - _createData.floorReservesPercent = floorReservesPercent; - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidFloorReservesPercent.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_floorReservesPercent_aboveMax_reverts( - uint24 floorReservesPercent_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - uint24 floorReservesPercent = - uint24(bound(floorReservesPercent_, 99e2 + 1, type(uint24).max)); - _createData.floorReservesPercent = floorReservesPercent; - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidFloorReservesPercent.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_anchorTickU_below_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the anchor range upper to be below the expected value - _createData.anchorTickU = _FIXED_PRICE_TICK_UPPER - 1; - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidAnchorTickUpper.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_anchorTickU_above_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the anchor range upper to be above the expected value - _createData.anchorTickU = _FIXED_PRICE_TICK_UPPER + 1; - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidAnchorTickUpper.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPrice_belowAuctionPrice_reverts() - public - givenPoolInitialTick(10_985) // Below auction price tick of 10986 - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_PoolLessThanAuctionPrice.selector, 10_985, 10_986 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPrice_aboveAuctionPrice() - public - givenPoolInitialTick(10_987) // Above auction price tick of 10986 - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - _assertTicks(10_987); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_floorRangeGap_belowBounds_reverts( - int24 floorRangeGap_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - int24 floorRangeGap = int24(bound(floorRangeGap_, type(int24).min, -1)); - _setFloorRangeGap(floorRangeGap); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_InvalidFloorRangeGap.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_floorRangeGap_underflow_reverts() - public - givenPoolInitialTick(TickMath.MIN_TICK + 200 * _ANCHOR_TICK_WIDTH) // This will result in the floor range to be below the MIN_TICK, which should cause a revert - givenAnchorUpperTick(-885_200) - givenPoolTargetTick(-885_300) - givenFloorRangeGap(1) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect a revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_RangeOutOfBounds.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_floorRangeGap_zero() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorRangeGap(0) - { - // Perform the call - _onCreate(); - - // Assert ticks - int24 fixedPriceTick = _getFixedPriceTick(); - _assertTicks(fixedPriceTick); - } - - function test_floorRangeGap_ten() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorRangeGap(10) - givenFloorReservesPercent(15e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert ticks - int24 fixedPriceTick = _getFixedPriceTick(); - _assertTicks(fixedPriceTick); - } - - function test_anchorTickWidth_belowBounds_reverts( - int24 anchorTickWidth_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - int24 anchorTickWidth = int24(bound(anchorTickWidth_, type(int24).min, 9)); - _setAnchorTickWidth(anchorTickWidth); - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidAnchorTickWidth.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_anchorTickWidth_aboveBounds_reverts( - int24 anchorTickWidth_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - int24 anchorTickWidth = int24(bound(anchorTickWidth_, 51, type(int24).max)); - _setAnchorTickWidth(anchorTickWidth); - - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidAnchorTickWidth.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_recipientZero_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the recipient to be the zero address - _createData.recipient = address(0); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_InvalidRecipient.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPercent_belowBounds_reverts( - uint24 poolPercent_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - uint24 poolPercent = uint24(bound(poolPercent_, 0, 10e2 - 1)); - _setPoolPercent(poolPercent); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_InvalidPoolPercent.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPercent_aboveBounds_reverts( - uint24 poolPercent_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - uint24 poolPercent = uint24(bound(poolPercent_, 100e2 + 1, type(uint24).max)); - _setPoolPercent(poolPercent); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_InvalidPoolPercent.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_givenAuctionFormatNotFixedPriceBatch_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionFormatIsEmp - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_UnsupportedAuctionFormat.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_auctionNotPrefunded_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_UnsupportedAuctionFormat.selector - ); - vm.expectRevert(err); - - // Perform the call - vm.prank(address(_auctionHouse)); - _dtl.onCreate( - _lotId, - _SELLER, - address(_baseToken), - address(_quoteToken), - _LOT_CAPACITY, - false, // Will revert as the auction is not prefunded - abi.encode(_createData) - ); - } - - function test_auctionPriceDoesNotMatchPoolActiveTick() - public - givenBPoolIsCreated // BPOOL will have an active tick of _FIXED_PRICE - givenCallbackIsCreated - givenFixedPrice(25e17) - givenAuctionIsCreated // Has to be after the fixed price is set - givenPoolPercent(99e2) // For the solvency check - givenFloorReservesPercent(90e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - // Fixed price = 2e18 - // SqrtPriceX96 = sqrt(2e18 * 2^192 / 1e18) - // = 1.12045542e29 - // Tick = log((1.12045542e29 / 2^96)^2) / log(1.0001) - // = 6,931.8183824009 (rounded down) - // Price = 1.0001^6931 / (10^(18-18)) = 1.9998363402 - int24 fixedPriceTick = 10_986; // Price: 3e18 - - _assertTicks(fixedPriceTick); - } - - function test_poolTargetTick_belowAnchorLowerTick_reverts( - int24 poolTargetTick_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - // Bound the pool target tick - int24 poolTargetTick = int24(bound(poolTargetTick_, type(int24).min, 8999)); // Below anchor lower tick of 9000 - _setPoolTargetTick(poolTargetTick); - - // Expect a revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidPoolTargetTick.selector, 9000, 11_000 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolTargetTick_aboveAnchorUpperTick_reverts( - int24 poolTargetTick_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - // Bound the pool target tick - int24 poolTargetTick = int24(bound(poolTargetTick_, 11_000, type(int24).max)); - _setPoolTargetTick(poolTargetTick); - - // Expect a revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_InvalidPoolTargetTick.selector, 9000, 11_000 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolTargetTick_fuzz( - int24 poolTargetTick_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated { - // Bound the pool target tick - int24 poolTargetTick = int24(bound(poolTargetTick_, 9000, 10_999)); - _setPoolTargetTick(poolTargetTick); - - // Perform the call - _onCreate(); - - // Assert pool target tick is set - assertEq(_dtl.poolTargetTick(), poolTargetTick, "pool target tick"); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Pool target tick is set - assertEq(_dtl.poolTargetTick(), _POOL_TARGET_TICK, "pool target tick"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_floorReservesPercent_low() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(10e2) - givenPoolPercent(91e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert - assertEq(_dtl.floorReservesPercent(), 10e2, "floor reserves percent"); - } - - function test_floorReservesPercent_low_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(10e2) - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 971_983_049_689_268_138 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_floorReservesPercent_middle() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(50e2) - { - // Perform the call - _onCreate(); - - // Assert - assertEq(_dtl.floorReservesPercent(), 50e2, "floor reserves percent"); - } - - function test_floorReservesPercent_high() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(99e2) - givenPoolPercent(82e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert - assertEq(_dtl.floorReservesPercent(), 99e2, "floor reserves percent"); - } - - function test_floorReservesPercent_high_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(99e2) - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 1_070_749_473_083_342_303 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPercent_lowPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(10e2) - givenFloorRangeGap(110) // For the solvency check - givenFloorReservesPercent(90e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert - assertEq(_dtl.poolPercent(), 10e2, "pool percent"); - } - - function test_poolPercent_lowPercent_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(10e2) - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 116_824_419_938_147_786 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_poolPercent_highPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(91e2) - givenFloorReservesPercent(10e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // Assert - assertEq(_dtl.poolPercent(), 91e2, "pool percent"); - } - - function test_poolPercent_highPercent_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(91e2) - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 1_063_102_221_437_144_855 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_feeTier500_reverts() - public - givenBPoolFeeTier(500) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(100e2) // For the solvency check - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_UnsupportedPoolFeeTier.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_feeTier3000_reverts() - public - givenBPoolFeeTier(3000) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(100e2) // For the solvency check - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_Params_UnsupportedPoolFeeTier.selector - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_auctionHighPrice() - public - givenFixedPrice(1e32) // Seems to cause a revert above this when calculating the tick - givenAnchorUpperTick(322_400) - givenPoolTargetTick(322_300) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // SqrtPriceX96 = sqrt(1e32 * 2^192 / 1e18) - // = 7.9456983992e35 - // Tick = log((7.9456983992e35 / 2^96)^2) / log(1.0001) - // = 322,435.7131383481 (rounded down) - // Price = 1.0001^322435 / (10^(18-18)) = 100,571,288,720,819.0986858653 - int24 fixedPriceTick = 322_378; // Not the exact tick, but close enough - - _assertTicks(fixedPriceTick); - } - - function test_auctionLowPrice() - public - givenFixedPrice(1e6) - givenAnchorUpperTick(-276_200) - givenPoolTargetTick(-276_300) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - // By default, quote token is token1 - // Fixed price = 1e6 - // SqrtPriceX96 = sqrt(1e6 * 2^192 / 1e18) - // = 7.9228162514e22 - // Tick = log((7.9228162514e22 / 2^96)^2) / log(1.0001) - // = -276,324.02643908 (rounded down) - // Price = 1.0001^-276,324.02643908 / (10^(18-18)) = 9.9999999999e-13 - int24 fixedPriceTick = -276_325; - - _assertTicks(fixedPriceTick); - } - - function test_narrowAnchorTickWidth() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - givenFloorReservesPercent(50e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - } - - function test_wideAnchorTickWidth() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(50) - givenFloorReservesPercent(10e2) // For the solvency check - givenPoolPercent(58e2) // For the solvency check - { - // Perform the call - _onCreate(); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - } - - function test_baseTokenAddressHigher_reverts() - public - givenBaseTokenAddressHigher - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_BPOOLInvalidAddress.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_baseTokenDecimalsHigher() - public - givenBaseTokenDecimals(19) - givenAnchorUpperTick(-12_000) - givenPoolTargetTick(-12_100) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq( - _baseToken.totalSupply(), _scaleBaseTokenAmount(_LOT_CAPACITY), "circulating supply" - ); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - } - - function test_baseTokenDecimalsLower() - public - givenBaseTokenDecimals(17) - givenAnchorUpperTick(34_200) - givenPoolTargetTick(34_100) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq( - _baseToken.totalSupply(), _scaleBaseTokenAmount(_LOT_CAPACITY), "circulating supply" - ); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - } - - function test_activeTickRounded() - public - givenBPoolFeeTier(10_000) - givenFixedPrice(1e18) - givenAnchorUpperTick(200) // Rounded up - givenPoolTargetTick(199) // Below anchor upper tick - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - int24 fixedPriceTick = 0; - - _assertTicks(fixedPriceTick); - } - - function test_anchorRange_overflow_reverts() - public - givenPoolInitialTick(TickMath.MAX_TICK - 1) // This will result in the upper tick of the anchor range to be above the MAX_TICK, which should cause a revert - givenAnchorUpperTick(887_400) - givenPoolTargetTick(887_300) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - { - // Expect a revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_RangeOutOfBounds.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_anchorRange_underflow_reverts() - public - givenPoolInitialTick(TickMath.MIN_TICK + 1) // This will result in the lower tick of the anchor range to be below the MIN_TICK, which should cause a revert - givenAnchorUpperTick(-887_200) - givenPoolTargetTick(-887_300) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - { - // Expect a revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_RangeOutOfBounds.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_discoveryRange_overflow_reverts() - public - givenPoolInitialTick(TickMath.MAX_TICK - _tickSpacing + 1) // This will result in the upper tick of the discovery range to be above the MAX_TICK, which should cause a revert - givenAnchorUpperTick(887_200) - givenPoolTargetTick(887_100) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - { - // Expect a revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_RangeOutOfBounds.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - // There are a few test scenarios that can't be tested: - // - The upper tick of the floor range is above the MAX_TICK: not possible, since that would require the pool to be initialised with a tick above the MAX_TICK - // - The lower tick of the discovery range is below the MIN_TICK: not possible, since that would require the pool to be initialised with a tick below the MIN_TICK - - function test_floorRange_underflow_reverts() - public - givenPoolInitialTick(TickMath.MIN_TICK) // This will result in the lower tick of the floor range to be below the MIN_TICK, which should cause a revert - givenAnchorUpperTick(-887_200) - givenPoolTargetTick(-887_300) - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - { - // Expect a revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_Params_RangeOutOfBounds.selector); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_givenProtocolFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(1e2) // 1% - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_givenProtocolFee_high_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(2e2) // 2% - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 996_045_004_392_648_025 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_givenReferrerFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenReferrerFeePercent(1e2) // 1% - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_givenReferrerFee_high_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenReferrerFeePercent(2e2) // 2% - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 996_045_004_392_648_025 - ); - vm.expectRevert(err); - - // Perform the call - _onCreate(); - } - - function test_givenProtocolFee_givenReferrerFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(5e1) // 0.5% - givenReferrerFeePercent(5e1) // 0.5% - { - // Perform the call - _onCreate(); - - // Assert base token balances - _assertBaseTokenBalances(); - - // Lot ID is set - assertEq(_dtl.lotId(), _lotId, "lot ID"); - - // Check circulating supply - assertEq(_baseToken.totalSupply(), _LOT_CAPACITY, "circulating supply"); - - // The pool should be initialised with the tick equivalent to the auction's fixed price - int24 fixedPriceTick = _getFixedPriceTick(); - - _assertTicks(fixedPriceTick); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_givenProtocolFee_givenReferrerFee_high_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(1e2) // 1% - givenReferrerFeePercent(1e2) // 1% - { - // Expect revert - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 996_045_004_392_648_025 - ); - vm.expectRevert(err); +*/ - // Perform the call - _onCreate(); - } +contract BaselineAxisLaunchOnCreateTest { +// Tests temporarily disabled } diff --git a/test/callbacks/liquidity/BaselineV2/onCurate.t.sol b/test/callbacks/liquidity/BaselineV2/onCurate.t.sol index d26bbaf6..2e72b018 100644 --- a/test/callbacks/liquidity/BaselineV2/onCurate.t.sol +++ b/test/callbacks/liquidity/BaselineV2/onCurate.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -90,3 +90,4 @@ contract BaselineOnCurateTest is BaselineAxisLaunchTest { assertEq(_baseToken.locked(), true, "transfer lock"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/onSettle.t.sol b/test/callbacks/liquidity/BaselineV2/onSettle.t.sol index 9dad3740..39175820 100644 --- a/test/callbacks/liquidity/BaselineV2/onSettle.t.sol +++ b/test/callbacks/liquidity/BaselineV2/onSettle.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; @@ -1095,3 +1095,4 @@ contract BaselineOnSettleTest is BaselineAxisLaunchTest { assertEq(_baseToken.locked(), true, "transfer lock"); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/slide.t.sol b/test/callbacks/liquidity/BaselineV2/slide.t.sol index 41b8d221..b8e90bd4 100644 --- a/test/callbacks/liquidity/BaselineV2/slide.t.sol +++ b/test/callbacks/liquidity/BaselineV2/slide.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; import {Range} from "@baseline/modules/BPOOL.v1.sol"; @@ -101,3 +101,4 @@ contract BaselineOnSettleSlideTest is BaselineAxisLaunchTest { console2.log("discovery upper", discoveryU); } } +*/ diff --git a/test/callbacks/liquidity/BaselineV2/sweep.t.sol b/test/callbacks/liquidity/BaselineV2/sweep.t.sol index 227e1025..eba88789 100644 --- a/test/callbacks/liquidity/BaselineV2/sweep.t.sol +++ b/test/callbacks/liquidity/BaselineV2/sweep.t.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; import {Range} from "@baseline/modules/BPOOL.v1.sol"; @@ -90,3 +90,4 @@ contract BaselineOnSettleSlideTest is BaselineAxisLaunchTest { console2.log("discovery upper", discoveryU); } } +*/ diff --git a/test/invariant/AxisInvariant.sol b/test/invariant/AxisInvariant.sol index 5b089365..49e64ca9 100644 --- a/test/invariant/AxisInvariant.sol +++ b/test/invariant/AxisInvariant.sol @@ -3,10 +3,10 @@ pragma solidity ^0.8.0; import {UniswapV2DTLHandler} from "./handlers/UniswapV2DTLHandler.sol"; import {UniswapV3DTLHandler} from "./handlers/UniswapV3DTLHandler.sol"; -import {BaselineDTLHandler} from "./handlers/BaselineDTLHandler.sol"; +// import {BaselineDTLHandler} from "./handlers/BaselineDTLHandler.sol"; import {V2PoolHandler} from "./handlers/V2PoolHandler.sol"; import {V3PoolHandler} from "./handlers/V3PoolHandler.sol"; -import {BaselinePoolHandler} from "./handlers/BaselinePoolHandler.sol"; +// import {BaselinePoolHandler} from "./handlers/BaselinePoolHandler.sol"; // forgefmt: disable-start /**************************************************************************************************************/ @@ -14,14 +14,14 @@ import {BaselinePoolHandler} from "./handlers/BaselinePoolHandler.sol"; /*** the Axis Fuzz Suite. ***/ /**************************************************************************************************************/ // forgefmt: disable-end -contract AxisInvariant is - UniswapV2DTLHandler, - UniswapV3DTLHandler, - BaselineDTLHandler, - V2PoolHandler, - V3PoolHandler, - BaselinePoolHandler -{ +// contract AxisInvariant is +// UniswapV2DTLHandler, +// UniswapV3DTLHandler, +// BaselineDTLHandler, +// V2PoolHandler, +// V3PoolHandler, +// BaselinePoolHandler +contract AxisInvariant is UniswapV2DTLHandler, UniswapV3DTLHandler, V2PoolHandler, V3PoolHandler { constructor() payable { setup(); } diff --git a/test/invariant/Setup.sol b/test/invariant/Setup.sol index c1b62db3..dc03f334 100644 --- a/test/invariant/Setup.sol +++ b/test/invariant/Setup.sol @@ -39,17 +39,17 @@ import {MockBatchAuctionModule} from import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.sol"; -import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; +// import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; // Baseline -import {Kernel, Actions, Module, toKeycode as toBaselineKeycode} from "@baseline/Kernel.sol"; +// import {Kernel, Actions, Module, toKeycode as toBaselineKeycode} from "@baseline/Kernel.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -import {BPOOLv1, Range, Position} from "@baseline/modules/BPOOL.v1.sol"; -import {BPOOLMinter} from "./modules/BPOOLMinter.sol"; -import {CREDTMinter} from "./modules/CREDTMinter.sol"; -import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; -import {LOOPSv1} from "@baseline/modules/LOOPS.v1.sol"; +// import {BPOOLv1, Range, Position} from "@baseline/modules/BPOOL.v1.sol"; +// import {BPOOLMinter} from "./modules/BPOOLMinter.sol"; +// import {CREDTMinter} from "./modules/CREDTMinter.sol"; +// import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; +// import {LOOPSv1} from "@baseline/modules/LOOPS.v1.sol"; import {ModuleTester, ModuleTestFixture} from "./modules/ModuleTester.sol"; import {WithSalts} from "../lib/WithSalts.sol"; @@ -62,7 +62,7 @@ import {MockBlast} from "./mocks/MockBlast.sol"; abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { using Callbacks for UniswapV2DirectToLiquidity; using Callbacks for UniswapV3DirectToLiquidity; - using Callbacks for BaselineAxisLaunch; + // using Callbacks for BaselineAxisLaunch; /*////////////////////////////////////////////////////////////////////////// GLOBAL VARIABLES @@ -132,11 +132,11 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { WETH9 internal _weth; SwapRouter internal _v3SwapRouter; - BaselineAxisLaunch internal _dtlBaseline; + // BaselineAxisLaunch internal _dtlBaseline; EncryptedMarginalPrice internal _empModule; FixedPriceBatch internal _fpbModule; - Kernel internal _kernel; + // Kernel internal _kernel; LinearVesting internal _linearVesting; MockBatchAuctionModule internal _batchAuctionModule; @@ -146,12 +146,12 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { MockERC20 internal _quoteToken; MockERC20 internal _baseToken; - BPOOLv1 internal _baselineToken; - CREDTv1 internal _credt; - LOOPSv1 internal _loops; + // BPOOLv1 internal _baselineToken; + // CREDTv1 internal _credt; + // LOOPSv1 internal _loops; - BPOOLMinter internal _bpoolMinter; - CREDTMinter internal _credtMinter; + // BPOOLMinter internal _bpoolMinter; + // CREDTMinter internal _credtMinter; /*////////////////////////////////////////////////////////////////////////// EVENTS @@ -259,69 +259,69 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { _updatePoolInitialTick(); - _kernel = new Kernel(); + // _kernel = new Kernel(); - _baselineToken = _deployBPOOL( - _kernel, - "Base Token", - "BT", - _baseTokenDecimals, - address(_uniV3Factory), - address(_quoteToken), - _feeTier, - _poolInitialTick, - address(_blast), - address(0) - ); + // _baselineToken = _deployBPOOL( + // _kernel, + // "Base Token", + // "BT", + // _baseTokenDecimals, + // address(_uniV3Factory), + // address(_quoteToken), + // _feeTier, + // _poolInitialTick, + // address(_blast), + // address(0) + // ); - _credt = new CREDTv1(_kernel, address(_blast), address(0)); + // _credt = new CREDTv1(_kernel, address(_blast), address(0)); - _loops = new LOOPSv1(_kernel, 1); + // _loops = new LOOPSv1(_kernel, 1); - _bpoolMinter = new BPOOLMinter(_kernel); - _credtMinter = new CREDTMinter(_kernel); + // _bpoolMinter = new BPOOLMinter(_kernel); + // _credtMinter = new CREDTMinter(_kernel); - _kernel.executeAction(Actions.InstallModule, address(_baselineToken)); - _kernel.executeAction(Actions.ActivatePolicy, address(_bpoolMinter)); + // _kernel.executeAction(Actions.InstallModule, address(_baselineToken)); + // _kernel.executeAction(Actions.ActivatePolicy, address(_bpoolMinter)); - _kernel.executeAction(Actions.InstallModule, address(_credt)); - _kernel.executeAction(Actions.ActivatePolicy, address(_credtMinter)); + // _kernel.executeAction(Actions.InstallModule, address(_credt)); + // _kernel.executeAction(Actions.ActivatePolicy, address(_credtMinter)); - _kernel.executeAction(Actions.InstallModule, address(_loops)); + // _kernel.executeAction(Actions.InstallModule, address(_loops)); - vm.prank(_OWNER); - _baselineAuctionHouse.installModule(_fpbModule); - vm.prank(_OWNER); - _baselineAuctionHouse.installModule(_empModule); + // vm.prank(_OWNER); + // _baselineAuctionHouse.installModule(_fpbModule); + // vm.prank(_OWNER); + // _baselineAuctionHouse.installModule(_empModule); - bytes memory baselineSaltArgs = abi.encodePacked( - type(BaselineAxisLaunch).creationCode, - abi.encode( - address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER - ) - ); + // bytes memory baselineSaltArgs = abi.encodePacked( + // type(BaselineAxisLaunch).creationCode, + // abi.encode( + // address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER + // ) + // ); - string[] memory baselineInputs = new string[](7); - baselineInputs[0] = "./test/invariant/helpers/salt_hash.sh"; - baselineInputs[1] = "--bytecodeHash"; - baselineInputs[2] = toHexString(keccak256(baselineSaltArgs)); - baselineInputs[3] = "--prefix"; - baselineInputs[4] = BASELINE_PREFIX; - baselineInputs[5] = "--deployer"; - baselineInputs[6] = toString(address(this)); + // string[] memory baselineInputs = new string[](7); + // baselineInputs[0] = "./test/invariant/helpers/salt_hash.sh"; + // baselineInputs[1] = "--bytecodeHash"; + // baselineInputs[2] = toHexString(keccak256(baselineSaltArgs)); + // baselineInputs[3] = "--prefix"; + // baselineInputs[4] = BASELINE_PREFIX; + // baselineInputs[5] = "--deployer"; + // baselineInputs[6] = toString(address(this)); - bytes memory baselineRes = vm.ffi(baselineInputs); - bytes32 baselineSalt = abi.decode(baselineRes, (bytes32)); + // bytes memory baselineRes = vm.ffi(baselineInputs); + // bytes32 baselineSalt = abi.decode(baselineRes, (bytes32)); - _dtlBaseline = new BaselineAxisLaunch{salt: baselineSalt}( - address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER - ); + // _dtlBaseline = new BaselineAxisLaunch{salt: baselineSalt}( + // address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER + // ); - _dtlBaselineAddress = address(_dtlBaseline); + // _dtlBaselineAddress = address(_dtlBaseline); - _bpoolMinter.setTransferLock(false); + // _bpoolMinter.setTransferLock(false); - _kernel.executeAction(Actions.ActivatePolicy, _dtlBaselineAddress); + // _kernel.executeAction(Actions.ActivatePolicy, _dtlBaselineAddress); } function randomAddress( @@ -366,106 +366,106 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { return TickMath.getTickAtSqrtRatio(sqrtPriceX96); } - function _deployBPOOL( - Kernel kernel_, - string memory _name, - string memory _symbol, - uint8 _decimals, - address _factory, - address _reserve, - uint24 _feeTier, - int24 _initialActiveTick, - address blast, - address blastGovernor - ) internal returns (BPOOLv1) { - bytes32 salt = _getSalt( - kernel_, - _name, - _symbol, - _decimals, - _factory, - _reserve, - _feeTier, - _initialActiveTick, - blast, - blastGovernor - ); - - return new BPOOLv1{salt: salt}( - kernel_, - _name, - _symbol, - _decimals, - _factory, - _reserve, - _feeTier, - _initialActiveTick, - blast, - blastGovernor - ); - } - - // Returns a salt that will result in a BPOOL address less than the reserve address - function _getSalt( - Kernel kernel_, - string memory _name, - string memory _symbol, - uint8 _decimals, - address _factory, - address _reserve, - uint24 _feeTier, - int24 _initialActiveTick, - address blast, - address blastGovernor - ) internal view returns (bytes32) { - uint256 salt; - - while (salt < 100) { - // Calculate the BPOOL bytecode hash - bytes32 BPOOLHash = keccak256( - abi.encodePacked( - type(BPOOLv1).creationCode, - abi.encode( - kernel_, - _name, - _symbol, - _decimals, - _factory, - _reserve, - _feeTier, - _initialActiveTick, - blast, - blastGovernor - ) - ) - ); - - // Calculate the BPOOL CREATE2 address - address BPOOLAddress = address( - uint160( - uint256( - keccak256( - abi.encodePacked( - bytes1(0xff), - address(this), // deployer address - bytes32(salt), - BPOOLHash - ) - ) - ) - ) - ); - - // Return the salt that will result in a BPOOL address less than the reserve address - if (BPOOLAddress < _reserve) { - return bytes32(salt); - } - - salt++; - } - - revert("No salt found"); - } + // function _deployBPOOL( + // Kernel kernel_, + // string memory _name, + // string memory _symbol, + // uint8 _decimals, + // address _factory, + // address _reserve, + // uint24 _feeTier, + // int24 _initialActiveTick, + // address blast, + // address blastGovernor + // ) internal returns (BPOOLv1) { + // bytes32 salt = _getSalt( + // kernel_, + // _name, + // _symbol, + // _decimals, + // _factory, + // _reserve, + // _feeTier, + // _initialActiveTick, + // blast, + // blastGovernor + // ); + + // return new BPOOLv1{salt: salt}( + // kernel_, + // _name, + // _symbol, + // _decimals, + // _factory, + // _reserve, + // _feeTier, + // _initialActiveTick, + // blast, + // blastGovernor + // ); + // } + + // // Returns a salt that will result in a BPOOL address less than the reserve address + // function _getSalt( + // Kernel kernel_, + // string memory _name, + // string memory _symbol, + // uint8 _decimals, + // address _factory, + // address _reserve, + // uint24 _feeTier, + // int24 _initialActiveTick, + // address blast, + // address blastGovernor + // ) internal view returns (bytes32) { + // uint256 salt; + + // while (salt < 100) { + // // Calculate the BPOOL bytecode hash + // bytes32 BPOOLHash = keccak256( + // abi.encodePacked( + // type(BPOOLv1).creationCode, + // abi.encode( + // kernel_, + // _name, + // _symbol, + // _decimals, + // _factory, + // _reserve, + // _feeTier, + // _initialActiveTick, + // blast, + // blastGovernor + // ) + // ) + // ); + + // // Calculate the BPOOL CREATE2 address + // address BPOOLAddress = address( + // uint160( + // uint256( + // keccak256( + // abi.encodePacked( + // bytes1(0xff), + // address(this), // deployer address + // bytes32(salt), + // BPOOLHash + // ) + // ) + // ) + // ) + // ); + + // // Return the salt that will result in a BPOOL address less than the reserve address + // if (BPOOLAddress < _reserve) { + // return bytes32(salt); + // } + + // salt++; + // } + + // revert("No salt found"); + // } function toString( address _addr @@ -493,30 +493,30 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { _baseToken.mint(address_, amount_); } - function givenAddressHasBaselineTokenBalance(address account_, uint256 amount_) internal { - _baselineToken.mint(account_, amount_); - } + // function givenAddressHasBaselineTokenBalance(address account_, uint256 amount_) internal { + // _baselineToken.mint(account_, amount_); + // } - function _disableTransferLock() internal { - _bpoolMinter.setTransferLock(false); - } + // function _disableTransferLock() internal { + // _bpoolMinter.setTransferLock(false); + // } - function _enableTransferLock() internal { - _bpoolMinter.setTransferLock(true); - } + // function _enableTransferLock() internal { + // _bpoolMinter.setTransferLock(true); + // } - function _transferBaselineTokenRefund( - uint256 amount_ - ) internal { - _disableTransferLock(); + // function _transferBaselineTokenRefund( + // uint256 amount_ + // ) internal { + // _disableTransferLock(); - // Transfer refund from auction house to the callback - // We transfer instead of minting to not affect the supply - vm.prank(address(_baselineAuctionHouse)); - _baselineToken.transfer(_dtlBaselineAddress, amount_); + // // Transfer refund from auction house to the callback + // // We transfer instead of minting to not affect the supply + // vm.prank(address(_baselineAuctionHouse)); + // _baselineToken.transfer(_dtlBaselineAddress, amount_); - _enableTransferLock(); - } + // _enableTransferLock(); + // } function givenAddressHasBaseTokenAllowance( address owner_, diff --git a/test/invariant/handlers/BaselineDTLHandler.sol b/test/invariant/handlers/BaselineDTLHandler.sol index c5b112d9..1d22323a 100644 --- a/test/invariant/handlers/BaselineDTLHandler.sol +++ b/test/invariant/handlers/BaselineDTLHandler.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; - +/* import {BeforeAfter} from "../helpers/BeforeAfter.sol"; import {Assertions} from "../helpers/Assertions.sol"; @@ -39,9 +39,9 @@ import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; import {FixedPointMathLib} from "@solmate-6.8.0/utils/FixedPointMathLib.sol"; abstract contract BaselineDTLHandler is BeforeAfter, Assertions { - /*////////////////////////////////////////////////////////////////////////// - HANDLER VARIABLES - //////////////////////////////////////////////////////////////////////////*/ + ////////////////////////////////////////////////////////////////////////// + // HANDLER VARIABLES + ////////////////////////////////////////////////////////////////////////// uint256 internal lotCapacity; @@ -58,9 +58,9 @@ abstract contract BaselineDTLHandler is BeforeAfter, Assertions { int24 internal _ANCHOR_TICK_U; uint24 internal _POOL_PERCENT; - /*////////////////////////////////////////////////////////////////////////// - TARGET FUNCTIONS - //////////////////////////////////////////////////////////////////////////*/ + ////////////////////////////////////////////////////////////////////////// + // TARGET FUNCTIONS + ////////////////////////////////////////////////////////////////////////// function baselineDTL_createLot() public { // PRE-CONDITIONS @@ -296,9 +296,9 @@ abstract contract BaselineDTLHandler is BeforeAfter, Assertions { } } - /*////////////////////////////////////////////////////////////////////////// - HELPERS - //////////////////////////////////////////////////////////////////////////*/ + ////////////////////////////////////////////////////////////////////////// + // HELPERS + ////////////////////////////////////////////////////////////////////////// function _scaleBaseTokenAmount( uint256 amount_ @@ -458,3 +458,4 @@ abstract contract BaselineDTLHandler is BeforeAfter, Assertions { ); } } +*/ diff --git a/test/invariant/handlers/BaselinePoolHandler.sol b/test/invariant/handlers/BaselinePoolHandler.sol index 08be6e44..ce9b3a84 100644 --- a/test/invariant/handlers/BaselinePoolHandler.sol +++ b/test/invariant/handlers/BaselinePoolHandler.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; - +/* import {BeforeAfter} from "../helpers/BeforeAfter.sol"; import {Assertions} from "../helpers/Assertions.sol"; @@ -78,3 +78,4 @@ abstract contract BaselinePoolHandler is BeforeAfter, Assertions { try _v3SwapRouter.exactInputSingle(params) {} catch {} } } +*/ diff --git a/test/invariant/helpers/BeforeAfter.sol b/test/invariant/helpers/BeforeAfter.sol index ff09b22f..b0a5017c 100644 --- a/test/invariant/helpers/BeforeAfter.sol +++ b/test/invariant/helpers/BeforeAfter.sol @@ -34,11 +34,11 @@ abstract contract BeforeAfter is Setup { _before.sellerQuoteBalance = _quoteToken.balanceOf(seller); _before.dtlBaseBalance = _baseToken.balanceOf(_dtlAddress); _before.auctionHouseBaseBalance = _baseToken.balanceOf(address(_auctionHouse)); - _before.sellerBaselineBalance = _baselineToken.balanceOf(seller); - _before.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); - _before.auctionHouseBaselineBalance = - _baselineToken.balanceOf(address(_baselineAuctionHouse)); - _before.baselineTotalSupply = _baselineToken.totalSupply(); + // _before.sellerBaselineBalance = _baselineToken.balanceOf(seller); + // _before.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); + // _before.auctionHouseBaselineBalance = + // _baselineToken.balanceOf(address(_baselineAuctionHouse)); + // _before.baselineTotalSupply = _baselineToken.totalSupply(); } function __after(uint96 lotId, address seller, address _dtlAddress) internal { @@ -49,11 +49,11 @@ abstract contract BeforeAfter is Setup { _after.sellerQuoteBalance = _quoteToken.balanceOf(seller); _after.dtlBaseBalance = _baseToken.balanceOf(_dtlAddress); _after.auctionHouseBaseBalance = _baseToken.balanceOf(address(_auctionHouse)); - _after.sellerBaselineBalance = _baselineToken.balanceOf(seller); - _after.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); - _after.auctionHouseBaselineBalance = - _baselineToken.balanceOf(address(_baselineAuctionHouse)); - _after.baselineTotalSupply = _baselineToken.totalSupply(); + // _after.sellerBaselineBalance = _baselineToken.balanceOf(seller); + // _after.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); + // _after.auctionHouseBaselineBalance = + // _baselineToken.balanceOf(address(_baselineAuctionHouse)); + // _after.baselineTotalSupply = _baselineToken.totalSupply(); } function _getDTLConfigurationV2( diff --git a/test/invariant/helpers/GuardianTester.sol b/test/invariant/helpers/GuardianTester.sol index 612d0eb3..61d03eb4 100644 --- a/test/invariant/helpers/GuardianTester.sol +++ b/test/invariant/helpers/GuardianTester.sol @@ -5,25 +5,30 @@ import {Test} from "@forge-std-1.9.1/Test.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; import {UniswapV2DTLHandler} from "../handlers/UniswapV2DTLHandler.sol"; import {UniswapV3DTLHandler} from "../handlers/UniswapV3DTLHandler.sol"; -import {BaselineDTLHandler} from "../handlers/BaselineDTLHandler.sol"; +// import {BaselineDTLHandler} from "../handlers/BaselineDTLHandler.sol"; import {V2PoolHandler} from "../handlers/V2PoolHandler.sol"; import {V3PoolHandler} from "../handlers/V3PoolHandler.sol"; -import {BaselinePoolHandler} from "../handlers/BaselinePoolHandler.sol"; +// import {BaselinePoolHandler} from "../handlers/BaselinePoolHandler.sol"; +// contract GuardianTester is +// UniswapV2DTLHandler, +// UniswapV3DTLHandler, +// BaselineDTLHandler, +// V2PoolHandler, +// V3PoolHandler, +// BaselinePoolHandler contract GuardianTester is UniswapV2DTLHandler, UniswapV3DTLHandler, - BaselineDTLHandler, V2PoolHandler, - V3PoolHandler, - BaselinePoolHandler + V3PoolHandler { function setUp() public { setup(); } function test_replay() public { - baselineDTL_createLot(); + // baselineDTL_createLot(); } function test_AX_52() public { @@ -57,12 +62,12 @@ contract GuardianTester is 12_825, 19_237_704_000 ); - baselineDTL_createLot(); - baselineDTL_onSettle( - 35_823_517_419_589_735_724_585_236_993_570_690_661_427_686_147_832_812, - 547_625_172_962_746_778_936_920_119_754_048_998_529_185_575_659_961_730_593_116, - 413_846_032_223_724_352_952_166_507_982_050_954_163_269_860_227_480_398_133, - 2_378_700_954_196_402_680_978_671_333_632_440_717_118_146_550_494 - ); + // baselineDTL_createLot(); + // baselineDTL_onSettle( + // 35_823_517_419_589_735_724_585_236_993_570_690_661_427_686_147_832_812, + // 547_625_172_962_746_778_936_920_119_754_048_998_529_185_575_659_961_730_593_116, + // 413_846_032_223_724_352_952_166_507_982_050_954_163_269_860_227_480_398_133, + // 2_378_700_954_196_402_680_978_671_333_632_440_717_118_146_550_494 + // ); } } diff --git a/test/invariant/modules/BPOOLMinter.sol b/test/invariant/modules/BPOOLMinter.sol index 61c9ddb2..51d5ba6a 100644 --- a/test/invariant/modules/BPOOLMinter.sol +++ b/test/invariant/modules/BPOOLMinter.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.19; - +/* import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; import {Kernel, Keycode, toKeycode, Policy, Permissions} from "@baseline/Kernel.sol"; @@ -36,3 +36,4 @@ contract BPOOLMinter is Policy, Owned { BPOOL.setTransferLock(lock_); } } +*/ diff --git a/test/invariant/modules/CREDTMinter.sol b/test/invariant/modules/CREDTMinter.sol index 1f7764ee..6e5bdafb 100644 --- a/test/invariant/modules/CREDTMinter.sol +++ b/test/invariant/modules/CREDTMinter.sol @@ -1,6 +1,6 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; - +/* import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; import {Kernel, Keycode, toKeycode, Policy} from "@baseline/Kernel.sol"; @@ -20,3 +20,4 @@ contract CREDTMinter is Policy, Owned { CREDT = CREDTv1(getModuleAddress(toKeycode("CREDT"))); } } +*/ From 50012d25c4d466613093562ef72ad66062d2dadc Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 16:07:00 +0400 Subject: [PATCH 03/19] Disable Baseline constants --- test/Constants.sol | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Constants.sol b/test/Constants.sol index 6d75548c..26e7415e 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -11,9 +11,9 @@ abstract contract TestConstants is TestConstantsCore { address internal constant _UNISWAP_V3_FACTORY = address(0xAA3023F92819f02180b25795a5797f69F3627Cb7); address internal constant _GUNI_FACTORY = address(0xAA19F2E4084fd3e49C198e616e181B82332000D5); - address internal constant _BASELINE_KERNEL = address(0xBB); - address internal constant _BASELINE_QUOTE_TOKEN = - address(0xAABA4a4ef5c3C62a3F40e61BC675331662dB4D96); + // address internal constant _BASELINE_KERNEL = address(0xBB); + // address internal constant _BASELINE_QUOTE_TOKEN = + // address(0xAABA4a4ef5c3C62a3F40e61BC675331662dB4D96); address internal constant _CREATE2_DEPLOYER = address(0x4e59b44847b379578588920cA78FbF26c0B4956C); From ae5a881e2dbe85a19b909033130f13d355837ca8 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 20:09:15 +0400 Subject: [PATCH 04/19] Fixed addresses for Uniswap V2 contracts in tests --- script/salts/test/TestSalts.s.sol | 18 ------------------ test/Constants.sol | 4 ++-- .../UniswapV2DTL/UniswapV2DTLTest.sol | 17 ++++------------- 3 files changed, 6 insertions(+), 33 deletions(-) diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol index 5584c65d..e7ad6838 100644 --- a/script/salts/test/TestSalts.s.sol +++ b/script/salts/test/TestSalts.s.sol @@ -175,24 +175,6 @@ contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConst _setTestSalt(bytecodePath, "90", _TOKEN_ALLOWLIST, bytecodeHash); } - function generateUniswapV2Router() public { - bytes memory args = abi.encode(_UNISWAP_V2_FACTORY, address(0)); - bytes memory contractCode = type(UniswapV2Router02).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode("UniswapV2Router", contractCode, args); - _setTestSalt(bytecodePath, "AA", "UniswapV2Router", bytecodeHash); - - // Fetch the salt that was set - bytes32 uniswapV2RouterSalt = _getSalt("Test_UniswapV2Router", contractCode, args); - - // Get the address of the UniswapV2Router - // Update the `_UNISWAP_V2_ROUTER` constant with this value - vm.prank(_CREATE2_DEPLOYER); - UniswapV2Router02 uniswapV2Router = - new UniswapV2Router02{salt: uniswapV2RouterSalt}(_UNISWAP_V2_FACTORY, address(0)); - console2.log("UniswapV2Router address: ", address(uniswapV2Router)); - } - function generateUniswapV2DirectToLiquidity() public { bytes memory args = abi.encode(_AUCTION_HOUSE, _UNISWAP_V2_FACTORY, _UNISWAP_V2_ROUTER); bytes memory contractCode = type(UniswapV2DirectToLiquidity).creationCode; diff --git a/test/Constants.sol b/test/Constants.sol index 26e7415e..525f7390 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -5,9 +5,9 @@ import {TestConstants as TestConstantsCore} from "@axis-core-1.0.4-test/Constant abstract contract TestConstants is TestConstantsCore { address internal constant _UNISWAP_V2_FACTORY = - address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); + address(0x222222); address internal constant _UNISWAP_V2_ROUTER = - address(0xAA063dB6d010722f4d29c000a8832f101b944570); + address(0x222333); address internal constant _UNISWAP_V3_FACTORY = address(0xAA3023F92819f02180b25795a5797f69F3627Cb7); address internal constant _GUNI_FACTORY = address(0xAA19F2E4084fd3e49C198e616e181B82332000D5); diff --git a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol index 87f3accb..37367f93 100644 --- a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol @@ -94,19 +94,10 @@ abstract contract UniswapV2DirectToLiquidityTest is Test, Permit2User, WithSalts // No storage slots to set // Create a UniswapV2Router at a deterministic address - vm.startBroadcast(); - bytes32 uniswapV2RouterSalt = _getTestSalt( - "UniswapV2Router", - type(UniswapV2Router02).creationCode, - abi.encode(address(_uniV2Factory), address(0)) - ); - _uniV2Router = - new UniswapV2Router02{salt: uniswapV2RouterSalt}(address(_uniV2Factory), address(0)); - vm.stopBroadcast(); - if (address(_uniV2Router) != _UNISWAP_V2_ROUTER) { - console2.log("UniswapV2Router address: {}", address(_uniV2Router)); - revert("UniswapV2Router address mismatch"); - } + UniswapV2Router02 uniV2Router = new UniswapV2Router02(address(_uniV2Factory), address(0)); + _uniV2Router = UniswapV2Router02(payable(_UNISWAP_V2_ROUTER)); + vm.etch(address(_uniV2Router), address(uniV2Router).code); + // No storage slots to set _linearVesting = new LinearVesting(address(_auctionHouse)); _batchAuctionModule = new MockBatchAuctionModule(address(_auctionHouse)); From 5d8197d68775f440b092c4b0572da963aa3464e5 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 20:17:09 +0400 Subject: [PATCH 05/19] Shift soldeer to use https for git repositories --- foundry.toml | 8 ++++---- soldeer.lock | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/foundry.toml b/foundry.toml index aa269609..0e07f9d6 100644 --- a/foundry.toml +++ b/foundry.toml @@ -48,9 +48,9 @@ axis-core = { version = "1.0.4" } "@openzeppelin-contracts-upgradeable" = { version = "4.9.2" } "@uniswap-v2-core" = { version = "1.0.1" } "@uniswap-v3-core" = { version = "1.0.1-solc-0.8-simulate" } -g-uni-v1-core = { version = "0.9.9", git = "git@github.com:Axis-Fi/g-uni-v1-core.git", rev = "d6bcb6e811e86d36bc836c002eb2e9a2c73d29ca" } -"@uniswap-v2-periphery" = { version = "1.0.1", git = "git@github.com:Axis-Fi/uniswap-v2-periphery.git", rev = "19be650786731dfe43cac3aac7a2d1f0731d18e2" } -"@uniswap-v3-periphery" = { version = "1.4.2-solc-0.8", git = "git@github.com:Uniswap/v3-periphery.git", rev = "b325bb0905d922ae61fcc7df85ee802e8df5e96c" } +g-uni-v1-core = { version = "0.9.9", git = "https://github.com/Axis-Fi/g-uni-v1-core.git", rev = "d6bcb6e811e86d36bc836c002eb2e9a2c73d29ca" } +"@uniswap-v2-periphery" = { version = "1.0.1", git = "https://github.com/Axis-Fi/uniswap-v2-periphery.git", rev = "19be650786731dfe43cac3aac7a2d1f0731d18e2" } +"@uniswap-v3-periphery" = { version = "1.4.2-solc-0.8", git = "https://github.com/Uniswap/v3-periphery.git", rev = "b325bb0905d922ae61fcc7df85ee802e8df5e96c" } solmate = { version = "6.8.0" } -clones-with-immutable-args = { version = "1.1.1", git = "git@github.com:wighawag/clones-with-immutable-args.git", rev = "f5ca191afea933d50a36d101009b5644dc28bc99" } +clones-with-immutable-args = { version = "1.1.1", git = "https://github.com/wighawag/clones-with-immutable-args.git", rev = "f5ca191afea933d50a36d101009b5644dc28bc99" } solady = { version = "0.0.124" } diff --git a/soldeer.lock b/soldeer.lock index b776b989..70ac43d5 100644 --- a/soldeer.lock +++ b/soldeer.lock @@ -22,7 +22,7 @@ integrity = "fda4e18a2a0c21eeddd8b6af36439f394e4ff74eb75705409a87b8952c9e2972" [[dependencies]] name = "@uniswap-v2-periphery" version = "1.0.1" -git = "git@github.com:Axis-Fi/uniswap-v2-periphery.git" +git = "https://github.com/Axis-Fi/uniswap-v2-periphery.git" rev = "19be650786731dfe43cac3aac7a2d1f0731d18e2" [[dependencies]] @@ -35,7 +35,7 @@ integrity = "75f26f8cb2cd8179eace9cdc4b248fa75faae799fc19c3e5a1f8f1b9d58d3188" [[dependencies]] name = "@uniswap-v3-periphery" version = "1.4.2-solc-0.8" -git = "git@github.com:Uniswap/v3-periphery.git" +git = "https://github.com/Uniswap/v3-periphery.git" rev = "b325bb0905d922ae61fcc7df85ee802e8df5e96c" [[dependencies]] @@ -48,7 +48,7 @@ integrity = "f4e2264ccfcdd763dcc0d73f7deb893da3f99afe0279e4d39dae508734b1c7fa" [[dependencies]] name = "clones-with-immutable-args" version = "1.1.1" -git = "git@github.com:wighawag/clones-with-immutable-args.git" +git = "https://github.com/wighawag/clones-with-immutable-args.git" rev = "f5ca191afea933d50a36d101009b5644dc28bc99" [[dependencies]] @@ -61,7 +61,7 @@ integrity = "389f8bfe6b6aad01915b1e38e6d4839f8189e8d4792b42be4e10d0a96a358e3f" [[dependencies]] name = "g-uni-v1-core" version = "0.9.9" -git = "git@github.com:Axis-Fi/g-uni-v1-core.git" +git = "https://github.com/Axis-Fi/g-uni-v1-core.git" rev = "d6bcb6e811e86d36bc836c002eb2e9a2c73d29ca" [[dependencies]] From 6100a284d7c051c9afbb18f4a8100b2bf05aa8e6 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 20:31:01 +0400 Subject: [PATCH 06/19] chore: update salts. All tests passing. --- script/salts/salts.json | 20 ++++++++++---------- test/Constants.sol | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/script/salts/salts.json b/script/salts/salts.json index 3c5f5059..f417ac15 100644 --- a/script/salts/salts.json +++ b/script/salts/salts.json @@ -80,8 +80,8 @@ "0xf758779927a94ce49a1ea7e126142cca8472adf8cc3133234411737bb193ce41": "0xe826d67a09b7f9d1da2beacf436b833ae46aae40524c788fd02a10b5c3258c9a" }, "Test_AllocatedMerkleAllowlist": { - "0x41f8d0682c0c351c9a7e3be972b89a4a9b23553b934088f1e2101118121941a3": "0x3f313929af4b1deb40049bb39ad51e7f198813b18390df284fe496b09bdd642d", - "0x994ced537007c38ba21c810d7c0fdf023088a818d02ecad3cdc94b4a95cc3375": "0x6b63033d73610d76bf58dc8809586115ce1efaedc4b0baf47d729261f15448d1" + "0x9e03fb2aace73c3f68d09982da20d6a08923251dc672c01d5812e26ea23e7550": "0xc6fb804b168aeb30de358cc401949dea5bf3ba88bcefeca8b93d1ce5254e4344", + "0xbc32424783b0d633ecd1a46a214002e55024976f7e52ef2af8d56b9ecf476e1b": "0x161b0468ae4354a7ae40f840816694f2134586857edd30470e9991acfe29cd25" }, "Test_BaselineAllocatedAllowlist": { "0x5412ed32372fa7e0c8212d5546300d8aaac1708e718fc1e28b9a6fde2f00c29c": "0x2642f239529f0d33043337522f0db56064be4b2f9f6c2c9cfc09d36f4930b293" @@ -99,11 +99,11 @@ "0xf2c9339adb8fd9d466007a94d111eeece37731dcaa121bf965ca1bd14efc8880": "0x964741c1ea1b8b404c1f4b232c9d601e739e05d59950fcb5f80544079520bfd3" }, "Test_CappedMerkleAllowlist": { - "0x8a937a02de69f5046e8e94209226bf7015b4343e59860dacbf566d6c4b31804d": "0xb4805f0fca79a90628ecd8767b58c247bb091972028eba1ef46598fba8c0bfe2", - "0xe06889fc2e4ca76544bbae409ee26361cedc9a5c91ab05d9080039bc93af72d5": "0x44868efcb3b1a0bbec6e19533da6a7d6dd8fa16cd464dcf866aba1c9e171932d" + "0x3541c3ae9de6032f4481ac375e8f8cab9c9c1ab8189ee6ac6ab97bd7e2748e46": "0xb6383b50128cdf2bff07f57fa822c784c69229358cc59ac3b595d0d93b62359a", + "0x9fbc09ca46d74ff6f6a7b68cb33f24fcabbcebe7f98f947adcfe26e80a92c1cd": "0xcc5e4ad6e00db37fa3283912386e35611d7f6543827e5c02954e9a37d125923a" }, "Test_GUniFactory": { - "0xac0379a57b230656f7c27bcd0873b98d6b461e55d26a3d95bc9be762fb6d55a0": "0x579256a43d33d926e621b1189bc7e40f50e7e8c4f1df2408299048fb3374e547" + "0x711113c26fdfc383a7d306c1fe0c9ba50729eb427a0c9ae3e1a42f95fac8b25b": "0xf309ee9b241232e5681c874fce188b08d000298bdf46e8a5cc0be516b73fa8be" }, "Test_QuoteToken": { "0x09d9ae22bfbfa131d639f287ea0015bc1b140c3fe1cc1929c4866bfba4f2c653": "0x9929415f26b845329bcee53f8a72154bac28bd08fd2cd3c8f455d61333eb93b4", @@ -112,20 +112,20 @@ "0xb24a3be6a8bdede031d12faa20163604d4e3ac83d74bd62343527c19d02d6bd7": "0x2cad71e04bcb4b291ee2c07deb5949371de1e15c0f0fe33b0d33ed63e8b10e44" }, "Test_TokenAllowlist": { - "0x1853ce437fe0aac47e6a27cf93d2340c89bbc9314a157f8b1385bc7647bcb1ce": "0x47e8d0004fab986ce099c83696d7c48700cab9e46fb0a08cedc5aa861783058c", - "0x71369782a004f899a09f30d15d07aea6e386231640ec5a67bf3f0ab2a7a335fe": "0xd546a781322897bd5be8fe859ddca634489f023edcc804545f0dc039f046cc2c" + "0x118b2f9b3657928d5b1848fade0ddc48dd50e9d65e683a363b653266870adaee": "0xb6e8c3e0c43f2d7cd25266fd1e3cd9786498c1ede5ecee6e2268a67fef120171", + "0x29e11e7edb0660ff55bd297aef1d1ad44c2a00eaee4c1dac7b9e5c9e5b85938e": "0x71d050b4c6e3a8f6e08c4c3886501335a1f44639031433cec645b8da7305360f" }, "Test_UniswapV2DirectToLiquidity": { - "0xf2b190e690a84e7be857af56398803943b855c7d589c61a9bb7795689a1f4086": "0x1446d0144b25261ce97bd9dfb74f095481741349546de789031f8189b39b687f" + "0x5648c9130a68e793e493c9f775617f4ebbff10e547a9e1cb15b43d61c8abc86e": "0x9d2b4c2da97b7ffe6d1b131380d95223b2eeaa53b474ba4d439c86faa1168114" }, "Test_UniswapV2Router": { "0x82202d1015ce048c53cd194a4407a02c152ee834d4b503f3dbd41d3799ee0dbb": "0x67226a40a6c0b7968e2cf7c37240a16ea7f3deb588c2421d67ce10cb4494de7e" }, "Test_UniswapV3DirectToLiquidity": { - "0x74a1f48af0886eb246c7a5ccd3fddc432320f2a6eab09cdeb998e4ea545bf8b4": "0x8d2eb44a9a6a44de1d0e1ccb0b9999633aaaf2bcf2b7b6671ec32b357939e645" + "0xd035f617c30775f0b66153027385d2fa109fa60e886f4b20d8de7d431bd64a78": "0x8a98b0c781361bd4e55135c6abb2d3acb524033c20f425b96b4f8aeec5512a69" }, "Test_UniswapV3Factory": { - "0xa56c03532e32af77794962a9477657f2caf39ad7070587c208fbf10ad705cf85": "0x19b9379f4d7172b3d99ce2f2bef5f3be5de1a581ed516956adcdf2f887aed861" + "0xd7d7fb682911c91b7e7df5ed01ce4da341bd2c8827fcbe2194bb528657a2984d": "0x37651652ec1265bc6df5f5abf562bdaec8f7d4a45df23c214f03ff9418ed4be7" }, "TokenAllowlist": { "0x09db47d395a68db033a3b222b9d1a212cec8422b03aeafc313aa4d2813c6dd60": "0xe07a005213f35e1f050a4da040d6bc3cae2ad333647b51a6ffa2e7941980043a", diff --git a/test/Constants.sol b/test/Constants.sol index 525f7390..43bcbbe0 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -9,8 +9,8 @@ abstract contract TestConstants is TestConstantsCore { address internal constant _UNISWAP_V2_ROUTER = address(0x222333); address internal constant _UNISWAP_V3_FACTORY = - address(0xAA3023F92819f02180b25795a5797f69F3627Cb7); - address internal constant _GUNI_FACTORY = address(0xAA19F2E4084fd3e49C198e616e181B82332000D5); + address(0xAAB5b268B35f9e63c0D88EEfacC89785cC3077d4); + address internal constant _GUNI_FACTORY = address(0xAA0a2E8B143d88f7C6480b3F5c7968F20eaE6753); // address internal constant _BASELINE_KERNEL = address(0xBB); // address internal constant _BASELINE_QUOTE_TOKEN = // address(0xAABA4a4ef5c3C62a3F40e61BC675331662dB4D96); From fed4ef48a2892db687c50b29c985a8164f546ea1 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 21:09:11 +0400 Subject: [PATCH 07/19] chore: linting --- test/Constants.sol | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/test/Constants.sol b/test/Constants.sol index 43bcbbe0..4ae77593 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -4,10 +4,8 @@ pragma solidity 0.8.19; import {TestConstants as TestConstantsCore} from "@axis-core-1.0.4-test/Constants.sol"; abstract contract TestConstants is TestConstantsCore { - address internal constant _UNISWAP_V2_FACTORY = - address(0x222222); - address internal constant _UNISWAP_V2_ROUTER = - address(0x222333); + address internal constant _UNISWAP_V2_FACTORY = address(0x222222); + address internal constant _UNISWAP_V2_ROUTER = address(0x222333); address internal constant _UNISWAP_V3_FACTORY = address(0xAAB5b268B35f9e63c0D88EEfacC89785cC3077d4); address internal constant _GUNI_FACTORY = address(0xAA0a2E8B143d88f7C6480b3F5c7968F20eaE6753); From f6322bb879d6d3869e021cfa91203d2b2aca299e Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 21:09:24 +0400 Subject: [PATCH 08/19] Script to generate and return salt --- script/salts/WithSalts.s.sol | 35 ++++++++++++++++++++ script/salts/generate_salt.sh | 60 +++++++++++++++++++++++++++++++++++ script/salts/write_salt.sh | 3 ++ 3 files changed, 98 insertions(+) create mode 100755 script/salts/generate_salt.sh diff --git a/script/salts/WithSalts.s.sol b/script/salts/WithSalts.s.sol index 2f5035f2..179d1ff0 100644 --- a/script/salts/WithSalts.s.sol +++ b/script/salts/WithSalts.s.sol @@ -50,6 +50,41 @@ contract WithSalts is Script { return (bytecodePath, bytecodeHash); } + function _generateSalt( + string memory contractName_, + bytes memory creationCode_, + bytes memory contractArgs_, + string memory prefix_ + ) internal returns (bytes32) { + // Write the bytecode + (string memory bytecodePath, bytes32 bytecodeHash) = + _writeBytecode(contractName_, creationCode_, contractArgs_); + + // Call the salts script to generate and return the salt + string[] memory inputs = new string[](9); + inputs[0] = "./script/salts/generate_salt.sh"; + inputs[1] = "--bytecodeFile"; + inputs[2] = bytecodePath; + inputs[3] = "--bytecodeHash"; + inputs[4] = vm.toString(bytecodeHash); + inputs[5] = "--prefix"; + inputs[6] = prefix_; + + bytes memory output = vm.ffi(inputs); + console2.log("Salt generated for", contractName_, "with prefix", prefix_); + console2.logBytes32(bytes32(output)); + + return bytes32(output); + } + + function _getTestSalt( + string memory contractName_, + bytes memory creationCode_, + bytes memory contractArgs_ + ) internal returns (bytes32) { + return _getSalt(string.concat("Test_", contractName_), creationCode_, contractArgs_); + } + /// @notice Gets the salt for a given key /// @dev If the key is not found, the function will return `bytes32(0)`. /// diff --git a/script/salts/generate_salt.sh b/script/salts/generate_salt.sh new file mode 100755 index 00000000..e24edbde --- /dev/null +++ b/script/salts/generate_salt.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# Usage: +# ./generate_salt.sh --bytecode --prefix --bytecodeHash [--deployer ] + +# Exit on error +set -e + +# Iterate through named arguments +# Source: https://unix.stackexchange.com/a/388038 +while [ $# -gt 0 ]; do + if [[ $1 == *"--"* ]]; then + v="${1/--/}" + declare $v="$2" + fi + + shift +done + +# Check if bytecodeFile is set +if [ -z "$bytecodeFile" ] +then + echo "No bytecode file specified. Provide the relative path after the command." + exit 1 +fi + +# Check if bytecodeFile exists +if [ ! -f "$bytecodeFile" ] +then + echo "Bytecode file ($bytecodeFile) not found. Provide the correct relative path after the command." + exit 1 +fi + +# Check if prefix is set +if [ -z "$prefix" ] +then + echo "No prefix specified. Provide the prefix after the bytecode file." + exit 1 +fi + +# Check if bytecodeHash is set +if [ -z "$bytecodeHash" ] +then + echo "No args hash specified. Provide the args hash after the salt key." + exit 1 +fi + +DEPLOYER_FLAG="" +if [ ! -z "$deployer" ] +then + DEPLOYER_FLAG="--deployer $deployer" +fi + +# Generate salt using cast create2 +output=$(cast create2 --case-sensitive --starts-with $prefix --init-code $(cat $bytecodeFile) $DEPLOYER_FLAG) + +# Get the first salt (as cast will often return the same salt multiple times) +salt=$(echo "$output" | grep 'Salt: ' | head -n 1 | awk -F' ' '{print $2}') + +echo "$salt" diff --git a/script/salts/write_salt.sh b/script/salts/write_salt.sh index 1ca8551c..d9ad6f93 100755 --- a/script/salts/write_salt.sh +++ b/script/salts/write_salt.sh @@ -3,6 +3,9 @@ # Usage: # ./write_salt.sh --bytecode --prefix --saltKey --bytecodeHash [--deployer ] +# Exit on error +set -e + # Iterate through named arguments # Source: https://unix.stackexchange.com/a/388038 while [ $# -gt 0 ]; do From b8f1ccfa0ee19276e6f623a6920a7a28da91ee1e Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:02:43 +0400 Subject: [PATCH 09/19] Modify allowlist tests to generate salts --- script/salts/test/TestSalts.s.sol | 115 ------------------ .../AllocatedMerkleAllowlistAtomic.t.sol | 12 +- .../AllocatedMerkleAllowlistBatch.t.sol | 12 +- .../CappedMerkleAllowlistAtomic.t.sol | 13 +- .../CappedMerkleAllowlistBatch.t.sol | 11 +- test/callbacks/TokenAllowlistAtomic.t.sol | 10 +- test/callbacks/TokenAllowlistBatch.t.sol | 10 +- 7 files changed, 43 insertions(+), 140 deletions(-) diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol index e7ad6838..4e18dc4b 100644 --- a/script/salts/test/TestSalts.s.sol +++ b/script/salts/test/TestSalts.s.sol @@ -60,121 +60,6 @@ contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConst require(success, string.concat("Failed to generate ", saltKey_)); } - function generateCappedMerkleAllowlist() public { - // 10001000 = 0x88 - bytes memory args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: false, - onBid: true, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - bytes memory contractCode = type(CappedMerkleAllowlist).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(_CAPPED_MERKLE_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "88", _CAPPED_MERKLE_ALLOWLIST, bytecodeHash); - - // 10010000 = 0x90 - args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: true, - onBid: false, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - (bytecodePath, bytecodeHash) = _writeBytecode(_CAPPED_MERKLE_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "90", _CAPPED_MERKLE_ALLOWLIST, bytecodeHash); - } - - function generateAllocatedMerkleAllowlist() public { - // 10001000 = 0x88 - bytes memory args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: false, - onBid: true, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - bytes memory contractCode = type(AllocatedMerkleAllowlist).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(_ALLOCATED_MERKLE_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "88", _ALLOCATED_MERKLE_ALLOWLIST, bytecodeHash); - - // 10010000 = 0x90 - args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: true, - onBid: false, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - (bytecodePath, bytecodeHash) = - _writeBytecode(_ALLOCATED_MERKLE_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "90", _ALLOCATED_MERKLE_ALLOWLIST, bytecodeHash); - } - - function generateTokenAllowlist() public { - // 10001000 = 0x88 - bytes memory args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: false, - onBid: true, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - bytes memory contractCode = type(TokenAllowlist).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(_TOKEN_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "88", _TOKEN_ALLOWLIST, bytecodeHash); - - // 10010000 = 0x90 - args = abi.encode( - _AUCTION_HOUSE, - Callbacks.Permissions({ - onCreate: true, - onCancel: false, - onCurate: false, - onPurchase: true, - onBid: false, - onSettle: false, - receiveQuoteTokens: false, - sendBaseTokens: false - }) - ); - (bytecodePath, bytecodeHash) = _writeBytecode(_TOKEN_ALLOWLIST, contractCode, args); - _setTestSalt(bytecodePath, "90", _TOKEN_ALLOWLIST, bytecodeHash); - } - function generateUniswapV2DirectToLiquidity() public { bytes memory args = abi.encode(_AUCTION_HOUSE, _UNISWAP_V2_FACTORY, _UNISWAP_V2_ROUTER); bytes memory contractCode = type(UniswapV2DirectToLiquidity).creationCode; diff --git a/test/callbacks/AllocatedMerkleAllowlistAtomic.t.sol b/test/callbacks/AllocatedMerkleAllowlistAtomic.t.sol index 6e8c6803..08b0dcd9 100644 --- a/test/callbacks/AllocatedMerkleAllowlistAtomic.t.sol +++ b/test/callbacks/AllocatedMerkleAllowlistAtomic.t.sol @@ -13,7 +13,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {AllocatedMerkleAllowlist} from "../../src/callbacks/allowlists/AllocatedMerkleAllowlist.sol"; import {toVeecode} from "@axis-core-1.0.4/modules/Keycode.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; contract AllocatedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, TestConstants { @@ -50,7 +50,7 @@ contract AllocatedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, Tes vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - // Get the salt + // Generate a salt for the contract Callbacks.Permissions memory permissions = Callbacks.Permissions({ onCreate: true, onCancel: false, @@ -61,9 +61,11 @@ contract AllocatedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, Tes receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = _getTestSalt( - "AllocatedMerkleAllowlist", type(AllocatedMerkleAllowlist).creationCode, args + bytes32 salt = _generateSalt( + "AtomicAllocatedMerkleAllowlist", + type(AllocatedMerkleAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "90" ); vm.broadcast(); diff --git a/test/callbacks/AllocatedMerkleAllowlistBatch.t.sol b/test/callbacks/AllocatedMerkleAllowlistBatch.t.sol index 85ae62c9..13efa959 100644 --- a/test/callbacks/AllocatedMerkleAllowlistBatch.t.sol +++ b/test/callbacks/AllocatedMerkleAllowlistBatch.t.sol @@ -13,7 +13,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {AllocatedMerkleAllowlist} from "../../src/callbacks/allowlists/AllocatedMerkleAllowlist.sol"; import {toVeecode} from "@axis-core-1.0.4/modules/Keycode.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; contract AllocatedMerkleAllowlistBatchTest is Test, Permit2User, WithSalts, TestConstants { @@ -50,7 +50,7 @@ contract AllocatedMerkleAllowlistBatchTest is Test, Permit2User, WithSalts, Test vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - // Get the salt + // Generate a salt for the contract Callbacks.Permissions memory permissions = Callbacks.Permissions({ onCreate: true, onCancel: false, @@ -61,9 +61,11 @@ contract AllocatedMerkleAllowlistBatchTest is Test, Permit2User, WithSalts, Test receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = _getTestSalt( - "AllocatedMerkleAllowlist", type(AllocatedMerkleAllowlist).creationCode, args + bytes32 salt = _generateSalt( + "BatchAllocatedMerkleAllowlist", + type(AllocatedMerkleAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "88" ); vm.broadcast(); diff --git a/test/callbacks/CappedMerkleAllowlistAtomic.t.sol b/test/callbacks/CappedMerkleAllowlistAtomic.t.sol index 50473a97..58a8ddcf 100644 --- a/test/callbacks/CappedMerkleAllowlistAtomic.t.sol +++ b/test/callbacks/CappedMerkleAllowlistAtomic.t.sol @@ -11,7 +11,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {CappedMerkleAllowlist} from "../../src/callbacks/allowlists/CappedMerkleAllowlist.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; contract CappedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, TestConstants { @@ -47,7 +47,7 @@ contract CappedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, TestCo vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - // Get the salt + // Generate a salt for the contract Callbacks.Permissions memory permissions = Callbacks.Permissions({ onCreate: true, onCancel: false, @@ -58,9 +58,12 @@ contract CappedMerkleAllowlistAtomicTest is Test, Permit2User, WithSalts, TestCo receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = - _getTestSalt("CappedMerkleAllowlist", type(CappedMerkleAllowlist).creationCode, args); + bytes32 salt = _generateSalt( + "AtomicCappedMerkleAllowlist", + type(CappedMerkleAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "90" + ); vm.broadcast(); _allowlist = new CappedMerkleAllowlist{salt: salt}(address(_auctionHouse), permissions); diff --git a/test/callbacks/CappedMerkleAllowlistBatch.t.sol b/test/callbacks/CappedMerkleAllowlistBatch.t.sol index 6a14afc8..bf7c0e29 100644 --- a/test/callbacks/CappedMerkleAllowlistBatch.t.sol +++ b/test/callbacks/CappedMerkleAllowlistBatch.t.sol @@ -11,7 +11,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {CappedMerkleAllowlist} from "../../src/callbacks/allowlists/CappedMerkleAllowlist.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; contract CappedMerkleAllowlistBatchTest is Test, Permit2User, WithSalts, TestConstants { @@ -58,9 +58,12 @@ contract CappedMerkleAllowlistBatchTest is Test, Permit2User, WithSalts, TestCon receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = - _getTestSalt("CappedMerkleAllowlist", type(CappedMerkleAllowlist).creationCode, args); + bytes32 salt = _generateSalt( + "BatchCappedMerkleAllowlist", + type(CappedMerkleAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "88" + ); vm.broadcast(); _allowlist = new CappedMerkleAllowlist{salt: salt}(address(_auctionHouse), permissions); diff --git a/test/callbacks/TokenAllowlistAtomic.t.sol b/test/callbacks/TokenAllowlistAtomic.t.sol index 69e11ab0..fcb90981 100644 --- a/test/callbacks/TokenAllowlistAtomic.t.sol +++ b/test/callbacks/TokenAllowlistAtomic.t.sol @@ -11,7 +11,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {TokenAllowlist, ITokenBalance} from "../../src/callbacks/allowlists/TokenAllowlist.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; @@ -56,8 +56,12 @@ contract TokenAllowlistAtomicTest is Test, Permit2User, WithSalts, TestConstants receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = _getTestSalt("TokenAllowlist", type(TokenAllowlist).creationCode, args); + bytes32 salt = _generateSalt( + "AtomicTokenAllowlist", + type(TokenAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "90" + ); vm.broadcast(); _allowlist = new TokenAllowlist{salt: salt}(address(_auctionHouse), permissions); diff --git a/test/callbacks/TokenAllowlistBatch.t.sol b/test/callbacks/TokenAllowlistBatch.t.sol index 7d6cc178..cc7ddd11 100644 --- a/test/callbacks/TokenAllowlistBatch.t.sol +++ b/test/callbacks/TokenAllowlistBatch.t.sol @@ -11,7 +11,7 @@ import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; import {TokenAllowlist, ITokenBalance} from "../../src/callbacks/allowlists/TokenAllowlist.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; @@ -56,8 +56,12 @@ contract TokenAllowlistBatchTest is Test, Permit2User, WithSalts, TestConstants receiveQuoteTokens: false, sendBaseTokens: false }); - bytes memory args = abi.encode(address(_auctionHouse), permissions); - bytes32 salt = _getTestSalt("TokenAllowlist", type(TokenAllowlist).creationCode, args); + bytes32 salt = _generateSalt( + "BatchTokenAllowlist", + type(TokenAllowlist).creationCode, + abi.encode(address(_auctionHouse), permissions), + "88" + ); vm.broadcast(); _allowlist = new TokenAllowlist{salt: salt}(address(_auctionHouse), permissions); From 6e2884cb8e105156ad49121b1de474ee13b943ef Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:16:32 +0400 Subject: [PATCH 10/19] Don't write contract bytecode if it already exists --- script/salts/WithSalts.s.sol | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/script/salts/WithSalts.s.sol b/script/salts/WithSalts.s.sol index 179d1ff0..76ba2972 100644 --- a/script/salts/WithSalts.s.sol +++ b/script/salts/WithSalts.s.sol @@ -17,9 +17,10 @@ contract WithSalts is Script { } function _getBytecodePath( - string memory name_ + string memory name_, + bytes32 bytecodeHash_ ) internal pure returns (string memory) { - return string.concat(_getBytecodeDirectory(), "/", name_, ".bin"); + return string.concat(_getBytecodeDirectory(), "/", name_, "-", vm.toString(bytecodeHash_), ".bin"); } function _createBytecodeDirectory() internal { @@ -44,7 +45,14 @@ contract WithSalts is Script { bytes memory bytecode = abi.encodePacked(creationCode_, contractArgs_); bytecodeHash = keccak256(bytecode); - bytecodePath = _getBytecodePath(contractName_); + bytecodePath = _getBytecodePath(contractName_, bytecodeHash); + + // Don't write the bytecode if it already exists + if (vm.isFile(bytecodePath)) { + console2.log("Skipping bytecode write for ", contractName_); + return (bytecodePath, bytecodeHash); + } + vm.writeFile(bytecodePath, vm.toString(bytecode)); return (bytecodePath, bytecodeHash); From e94cebf54c868e89bcd0a16b6aeb0907f61bd4da Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:18:40 +0400 Subject: [PATCH 11/19] Generate salts for Uniswap tests --- .../callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol | 8 ++++---- .../callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol index 37367f93..e1847768 100644 --- a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol @@ -25,7 +25,7 @@ import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.so import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -import {WithSalts} from "../../../lib/WithSalts.sol"; +import {WithSalts} from "../../../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../../../Constants.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; @@ -119,11 +119,11 @@ abstract contract UniswapV2DirectToLiquidityTest is Test, Permit2User, WithSalts } modifier givenCallbackIsCreated() { - // Get the salt + // Generate a salt for the contract bytes memory args = abi.encode(address(_auctionHouse), address(_uniV2Factory), address(_uniV2Router)); - bytes32 salt = _getTestSalt( - "UniswapV2DirectToLiquidity", type(UniswapV2DirectToLiquidity).creationCode, args + bytes32 salt = _generateSalt( + "UniswapV2DirectToLiquidity", type(UniswapV2DirectToLiquidity).creationCode, args, "E6" ); // Required for CREATE2 address to work correctly. doesn't do anything in a test diff --git a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol index eb2c0561..87c4f317 100644 --- a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol @@ -26,7 +26,7 @@ import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.so import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -import {WithSalts} from "../../../lib/WithSalts.sol"; +import {WithSalts} from "../../../../script/salts/WithSalts.s.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; import {TestConstants} from "../../../Constants.sol"; @@ -139,11 +139,11 @@ abstract contract UniswapV3DirectToLiquidityTest is Test, Permit2User, WithSalts } modifier givenCallbackIsCreated() { - // Get the salt + // Generate a salt for the contract bytes memory args = abi.encode(address(_auctionHouse), address(_uniV3Factory), address(_gUniFactory)); - bytes32 salt = _getTestSalt( - "UniswapV3DirectToLiquidity", type(UniswapV3DirectToLiquidity).creationCode, args + bytes32 salt = _generateSalt( + "UniswapV3DirectToLiquidity", type(UniswapV3DirectToLiquidity).creationCode, args, "E6" ); // Required for CREATE2 address to work correctly. doesn't do anything in a test From 7eb390c1edf4c0fcd868742e99c9fb7abda4a6ae Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:21:24 +0400 Subject: [PATCH 12/19] chore: linting --- script/salts/WithSalts.s.sol | 4 ++- script/salts/test/TestSalts.s.sol | 26 ------------------- .../UniswapV2DTL/UniswapV2DTLTest.sol | 1 - 3 files changed, 3 insertions(+), 28 deletions(-) diff --git a/script/salts/WithSalts.s.sol b/script/salts/WithSalts.s.sol index 76ba2972..52e6fcae 100644 --- a/script/salts/WithSalts.s.sol +++ b/script/salts/WithSalts.s.sol @@ -20,7 +20,9 @@ contract WithSalts is Script { string memory name_, bytes32 bytecodeHash_ ) internal pure returns (string memory) { - return string.concat(_getBytecodeDirectory(), "/", name_, "-", vm.toString(bytecodeHash_), ".bin"); + return string.concat( + _getBytecodeDirectory(), "/", name_, "-", vm.toString(bytecodeHash_), ".bin" + ); } function _createBytecodeDirectory() internal { diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol index 4e18dc4b..f0e43269 100644 --- a/script/salts/test/TestSalts.s.sol +++ b/script/salts/test/TestSalts.s.sol @@ -10,21 +10,11 @@ import {TestConstants} from "../../../test/Constants.sol"; // Libraries import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; -import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; // Uniswap import {UniswapV3Factory} from "../../../test/lib/uniswap-v3/UniswapV3Factory.sol"; import {GUniFactory} from "@g-uni-v1-core-0.9.9/GUniFactory.sol"; -import {UniswapV2Router02} from "@uniswap-v2-periphery-1.0.1/UniswapV2Router02.sol"; - -// Callbacks -import {CappedMerkleAllowlist} from "../../../src/callbacks/allowlists/CappedMerkleAllowlist.sol"; -import {AllocatedMerkleAllowlist} from - "../../../src/callbacks/allowlists/AllocatedMerkleAllowlist.sol"; -import {TokenAllowlist} from "../../../src/callbacks/allowlists/TokenAllowlist.sol"; -import {UniswapV2DirectToLiquidity} from "../../../src/callbacks/liquidity/UniswapV2DTL.sol"; -import {UniswapV3DirectToLiquidity} from "../../../src/callbacks/liquidity/UniswapV3DTL.sol"; // import {BaselineAxisLaunch} from // "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; @@ -60,22 +50,6 @@ contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConst require(success, string.concat("Failed to generate ", saltKey_)); } - function generateUniswapV2DirectToLiquidity() public { - bytes memory args = abi.encode(_AUCTION_HOUSE, _UNISWAP_V2_FACTORY, _UNISWAP_V2_ROUTER); - bytes memory contractCode = type(UniswapV2DirectToLiquidity).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode("UniswapV2DirectToLiquidity", contractCode, args); - _setTestSalt(bytecodePath, "E6", "UniswapV2DirectToLiquidity", bytecodeHash); - } - - function generateUniswapV3DirectToLiquidity() public { - bytes memory args = abi.encode(_AUCTION_HOUSE, _UNISWAP_V3_FACTORY, _GUNI_FACTORY); - bytes memory contractCode = type(UniswapV3DirectToLiquidity).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode("UniswapV3DirectToLiquidity", contractCode, args); - _setTestSalt(bytecodePath, "E6", "UniswapV3DirectToLiquidity", bytecodeHash); - } - function generateGUniFactory() public { // Generate a salt for a GUniFactory bytes memory args = abi.encode(_UNISWAP_V3_FACTORY); diff --git a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol index e1847768..f2f30551 100644 --- a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol @@ -27,7 +27,6 @@ import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; import {WithSalts} from "../../../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../../../Constants.sol"; -import {console2} from "@forge-std-1.9.1/console2.sol"; abstract contract UniswapV2DirectToLiquidityTest is Test, Permit2User, WithSalts, TestConstants { using Callbacks for UniswapV2DirectToLiquidity; From dd4fc9bd3c69455c96999fbbf1a2ccad0b6a8455 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:28:55 +0400 Subject: [PATCH 13/19] Remove obsolete WithSalts helper --- script/salts/test/TestSalts.s.sol | 76 +++++-------------- test/Constants.sol | 3 - .../UniswapV2DTL/UniswapV2DTLTest.sol | 20 +++-- .../UniswapV3DTL/UniswapV3DTLTest.sol | 21 +---- test/invariant/Setup.sol | 2 +- test/lib/WithSalts.sol | 44 ----------- 6 files changed, 31 insertions(+), 135 deletions(-) delete mode 100644 test/lib/WithSalts.sol diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol index f0e43269..cfe1210f 100644 --- a/script/salts/test/TestSalts.s.sol +++ b/script/salts/test/TestSalts.s.sol @@ -12,10 +12,6 @@ import {TestConstants} from "../../../test/Constants.sol"; import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -// Uniswap -import {UniswapV3Factory} from "../../../test/lib/uniswap-v3/UniswapV3Factory.sol"; -import {GUniFactory} from "@g-uni-v1-core-0.9.9/GUniFactory.sol"; - // import {BaselineAxisLaunch} from // "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; // import {BALwithAllocatedAllowlist} from @@ -50,63 +46,25 @@ contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConst require(success, string.concat("Failed to generate ", saltKey_)); } - function generateGUniFactory() public { - // Generate a salt for a GUniFactory - bytes memory args = abi.encode(_UNISWAP_V3_FACTORY); - bytes memory contractCode = type(GUniFactory).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode("GUniFactory", contractCode, args); - _setTestSaltWithDeployer(bytecodePath, "AA", "GUniFactory", bytecodeHash, _CREATE2_DEPLOYER); - - // Fetch the salt that was set - bytes32 gUniFactorySalt = _getSalt("Test_GUniFactory", contractCode, args); - - // Get the address of the GUniFactory - // Update the `_GUNI_FACTORY` constant with this value - vm.prank(_CREATE2_DEPLOYER); - GUniFactory gUniFactory = new GUniFactory{salt: gUniFactorySalt}(_UNISWAP_V3_FACTORY); - console2.log("GUniFactory address: ", address(gUniFactory)); - } + // function generateBaselineQuoteToken() public { + // // Generate a salt for a MockERC20 quote token + // bytes memory qtArgs = abi.encode("Quote Token", "QT", 18); + // bytes memory qtContractCode = type(MockERC20).creationCode; + // (string memory qtBytecodePath, bytes32 qtBytecodeHash) = + // _writeBytecode("QuoteToken", qtContractCode, qtArgs); + // _setTestSaltWithDeployer( + // qtBytecodePath, "AA", "QuoteToken", qtBytecodeHash, _CREATE2_DEPLOYER + // ); - function generateUniswapV3Factory() public { - // Generate a salt for a GUniFactory - bytes memory args = abi.encode(); - bytes memory contractCode = type(UniswapV3Factory).creationCode; - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode("UniswapV3Factory", contractCode, args); - _setTestSaltWithDeployer( - bytecodePath, "AA", "UniswapV3Factory", bytecodeHash, _CREATE2_DEPLOYER - ); - - // Fetch the salt that was set - bytes32 uniswapV3FactorySalt = _getSalt("Test_UniswapV3Factory", contractCode, args); - - // Get the address of the UniswapV3Factory - // Update the `_UNISWAP_V3_FACTORY` constant with this value - vm.prank(_CREATE2_DEPLOYER); - UniswapV3Factory uniswapV3Factory = new UniswapV3Factory{salt: uniswapV3FactorySalt}(); - console2.log("UniswapV3Factory address: ", address(uniswapV3Factory)); - } + // // Fetch the salt that was set + // bytes32 quoteTokenSalt = _getSalt("Test_QuoteToken", qtContractCode, qtArgs); - function generateBaselineQuoteToken() public { - // Generate a salt for a MockERC20 quote token - bytes memory qtArgs = abi.encode("Quote Token", "QT", 18); - bytes memory qtContractCode = type(MockERC20).creationCode; - (string memory qtBytecodePath, bytes32 qtBytecodeHash) = - _writeBytecode("QuoteToken", qtContractCode, qtArgs); - _setTestSaltWithDeployer( - qtBytecodePath, "AA", "QuoteToken", qtBytecodeHash, _CREATE2_DEPLOYER - ); - - // Fetch the salt that was set - bytes32 quoteTokenSalt = _getSalt("Test_QuoteToken", qtContractCode, qtArgs); - - // Get the address of the quote token - // Update the `_BASELINE_QUOTE_TOKEN` constants with this value - vm.prank(_CREATE2_DEPLOYER); - MockERC20 quoteToken = new MockERC20{salt: quoteTokenSalt}("Quote Token", "QT", 18); - console2.log("Quote Token address: ", address(quoteToken)); - } + // // Get the address of the quote token + // // Update the `_BASELINE_QUOTE_TOKEN` constants with this value + // vm.prank(_CREATE2_DEPLOYER); + // MockERC20 quoteToken = new MockERC20{salt: quoteTokenSalt}("Quote Token", "QT", 18); + // console2.log("Quote Token address: ", address(quoteToken)); + // } // function generateBaselineAxisLaunch() public { // // Get the salt diff --git a/test/Constants.sol b/test/Constants.sol index 4ae77593..2be22ab7 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -4,11 +4,8 @@ pragma solidity 0.8.19; import {TestConstants as TestConstantsCore} from "@axis-core-1.0.4-test/Constants.sol"; abstract contract TestConstants is TestConstantsCore { - address internal constant _UNISWAP_V2_FACTORY = address(0x222222); - address internal constant _UNISWAP_V2_ROUTER = address(0x222333); address internal constant _UNISWAP_V3_FACTORY = address(0xAAB5b268B35f9e63c0D88EEfacC89785cC3077d4); - address internal constant _GUNI_FACTORY = address(0xAA0a2E8B143d88f7C6480b3F5c7968F20eaE6753); // address internal constant _BASELINE_KERNEL = address(0xBB); // address internal constant _BASELINE_QUOTE_TOKEN = // address(0xAABA4a4ef5c3C62a3F40e61BC675331662dB4D96); diff --git a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol index f2f30551..44773ec3 100644 --- a/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV2DTL/UniswapV2DTLTest.sol @@ -86,17 +86,15 @@ abstract contract UniswapV2DirectToLiquidityTest is Test, Permit2User, WithSalts vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - // Create a UniswapV2Factory at a deterministic address - UniswapV2FactoryClone uniV2Factory = new UniswapV2FactoryClone(); - _uniV2Factory = UniswapV2FactoryClone(_UNISWAP_V2_FACTORY); - vm.etch(address(_uniV2Factory), address(uniV2Factory).code); - // No storage slots to set - - // Create a UniswapV2Router at a deterministic address - UniswapV2Router02 uniV2Router = new UniswapV2Router02(address(_uniV2Factory), address(0)); - _uniV2Router = UniswapV2Router02(payable(_UNISWAP_V2_ROUTER)); - vm.etch(address(_uniV2Router), address(uniV2Router).code); - // No storage slots to set + // Create a UniswapV2Factory + vm.startBroadcast(_CREATE2_DEPLOYER); + _uniV2Factory = new UniswapV2FactoryClone(); + vm.stopBroadcast(); + + // Create a UniswapV2Router + vm.startBroadcast(_CREATE2_DEPLOYER); + _uniV2Router = new UniswapV2Router02(address(_uniV2Factory), address(0)); + vm.stopBroadcast(); _linearVesting = new LinearVesting(address(_auctionHouse)); _batchAuctionModule = new MockBatchAuctionModule(address(_auctionHouse)); diff --git a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol index 87c4f317..b4d897b9 100644 --- a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol @@ -91,28 +91,15 @@ abstract contract UniswapV3DirectToLiquidityTest is Test, Permit2User, WithSalts vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - // Create a UniswapV3Factory at a deterministic address + // Create a UniswapV3Factory vm.startBroadcast(_CREATE2_DEPLOYER); - bytes32 uniswapV3Salt = - _getTestSalt("UniswapV3Factory", type(UniswapV3Factory).creationCode, abi.encode()); - _uniV3Factory = new UniswapV3Factory{salt: uniswapV3Salt}(); + _uniV3Factory = new UniswapV3Factory(); vm.stopBroadcast(); - if (address(_uniV3Factory) != _UNISWAP_V3_FACTORY) { - console2.log("UniswapV3Factory address: ", address(_uniV3Factory)); - revert("UniswapV3Factory address mismatch"); - } - // Create a GUniFactory at a deterministic address + // Create a GUniFactory vm.startBroadcast(_CREATE2_DEPLOYER); - bytes32 gUniFactorySalt = _getTestSalt( - "GUniFactory", type(GUniFactory).creationCode, abi.encode(address(_uniV3Factory)) - ); - _gUniFactory = new GUniFactory{salt: gUniFactorySalt}(address(_uniV3Factory)); + _gUniFactory = new GUniFactory(address(_uniV3Factory)); vm.stopBroadcast(); - if (address(_gUniFactory) != _GUNI_FACTORY) { - console2.log("GUniFactory address: ", address(_gUniFactory)); - revert("GUniFactory address mismatch"); - } // Initialize the GUniFactory address payable gelatoAddress = payable(address(0x10)); diff --git a/test/invariant/Setup.sol b/test/invariant/Setup.sol index dc03f334..ed294275 100644 --- a/test/invariant/Setup.sol +++ b/test/invariant/Setup.sol @@ -52,7 +52,7 @@ import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; // import {LOOPSv1} from "@baseline/modules/LOOPS.v1.sol"; import {ModuleTester, ModuleTestFixture} from "./modules/ModuleTester.sol"; -import {WithSalts} from "../lib/WithSalts.sol"; +import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; diff --git a/test/lib/WithSalts.sol b/test/lib/WithSalts.sol deleted file mode 100644 index d4eec62c..00000000 --- a/test/lib/WithSalts.sol +++ /dev/null @@ -1,44 +0,0 @@ -/// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; - -import {Test} from "@forge-std-1.9.1/Test.sol"; -import {stdJson} from "@forge-std-1.9.1/StdJson.sol"; - -contract WithSalts is Test { - using stdJson for string; - - string internal constant _SALTS_PATH = "./script/salts/salts.json"; - string internal _saltJson; - - /// @notice Gets the salt for a given key - /// @dev Test salts are read from underneath the ".test" prefix. - /// - /// If the key is not found, the function will return `bytes32(0)`. - /// - /// @param contractName_ The contract to get the salt for - /// @param contractCode_ The creation code of the contract - /// @param args_ The abi-encoded constructor arguments to the contract - /// @return The salt for the given key - function _getTestSalt( - string memory contractName_, - bytes memory contractCode_, - bytes memory args_ - ) internal returns (bytes32) { - // Load salt file if needed - if (bytes(_saltJson).length == 0) { - _saltJson = vm.readFile(_SALTS_PATH); - } - - // Generate the bytecode hash - bytes memory bytecode = abi.encodePacked(contractCode_, args_); - bytes32 bytecodeHash = keccak256(bytecode); - - bytes32 salt = bytes32( - vm.parseJson( - _saltJson, string.concat(".Test_", contractName_, ".", vm.toString(bytecodeHash)) - ) - ); - - return salt; - } -} From e4649bcadd3c9cdf01e0e6d632a4f47645874bf7 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:35:48 +0400 Subject: [PATCH 14/19] Remove obsolete test salts --- script/salts/salts.json | 48 ----------------------------------------- 1 file changed, 48 deletions(-) diff --git a/script/salts/salts.json b/script/salts/salts.json index f417ac15..236ef722 100644 --- a/script/salts/salts.json +++ b/script/salts/salts.json @@ -79,54 +79,6 @@ "0xed4ba02077e70f78db70ce191509333d2dcccfff136d30dcb011f567305e88ad": "0x2b8bc588174d409692f1bd993942e3806c9a11344dbe674f46aed32a030aacf1", "0xf758779927a94ce49a1ea7e126142cca8472adf8cc3133234411737bb193ce41": "0xe826d67a09b7f9d1da2beacf436b833ae46aae40524c788fd02a10b5c3258c9a" }, - "Test_AllocatedMerkleAllowlist": { - "0x9e03fb2aace73c3f68d09982da20d6a08923251dc672c01d5812e26ea23e7550": "0xc6fb804b168aeb30de358cc401949dea5bf3ba88bcefeca8b93d1ce5254e4344", - "0xbc32424783b0d633ecd1a46a214002e55024976f7e52ef2af8d56b9ecf476e1b": "0x161b0468ae4354a7ae40f840816694f2134586857edd30470e9991acfe29cd25" - }, - "Test_BaselineAllocatedAllowlist": { - "0x5412ed32372fa7e0c8212d5546300d8aaac1708e718fc1e28b9a6fde2f00c29c": "0x2642f239529f0d33043337522f0db56064be4b2f9f6c2c9cfc09d36f4930b293" - }, - "Test_BaselineAllowlist": { - "0x7ff91cb07667005944b41d30d1cf5e19b36a1dc0483d48a614b214c7e7993069": "0x92988881f5f3199b14f8d4a42b0288cc0b03a79203d5e1738a4a85c4350dac74" - }, - "Test_BaselineAxisLaunch": { - "0x015efa4d0b39ebe205ba61d345d7a03b24bc55c7c8f7b71a9f7a0310f21371c6": "0x6f68298618b6ad68ec9c1946483b1b2e3d66b7b69e9899446dcc07c7e8651d05" - }, - "Test_BaselineCappedAllowlist": { - "0x61519e45b65ed982ee364cbc91ece9f0030e8c8747995c16d485cfe2f09eb5b3": "0xd4e819a632dacb901e456cfd37f5569cf5ef94fedd7f1bf9202aa1443a8afe2c" - }, - "Test_BaselineTokenAllowlist": { - "0xf2c9339adb8fd9d466007a94d111eeece37731dcaa121bf965ca1bd14efc8880": "0x964741c1ea1b8b404c1f4b232c9d601e739e05d59950fcb5f80544079520bfd3" - }, - "Test_CappedMerkleAllowlist": { - "0x3541c3ae9de6032f4481ac375e8f8cab9c9c1ab8189ee6ac6ab97bd7e2748e46": "0xb6383b50128cdf2bff07f57fa822c784c69229358cc59ac3b595d0d93b62359a", - "0x9fbc09ca46d74ff6f6a7b68cb33f24fcabbcebe7f98f947adcfe26e80a92c1cd": "0xcc5e4ad6e00db37fa3283912386e35611d7f6543827e5c02954e9a37d125923a" - }, - "Test_GUniFactory": { - "0x711113c26fdfc383a7d306c1fe0c9ba50729eb427a0c9ae3e1a42f95fac8b25b": "0xf309ee9b241232e5681c874fce188b08d000298bdf46e8a5cc0be516b73fa8be" - }, - "Test_QuoteToken": { - "0x09d9ae22bfbfa131d639f287ea0015bc1b140c3fe1cc1929c4866bfba4f2c653": "0x9929415f26b845329bcee53f8a72154bac28bd08fd2cd3c8f455d61333eb93b4", - "0x444caed4e1704bd9e214cb6c8a562f99e8806c74185f0debc4dca8dda3002ebb": "0xc53b4a2c323d99618c23aad7238495234e5eaddba872f3d079aa082872e098c5", - "0x58fea475f289c0e3fcddb49b7900555f1a11d4b36caf2f735992776e1d007bba": "0x312f8d3dce539794a883e359491df7844e21233914dd4343fb483c44eeea3709", - "0xb24a3be6a8bdede031d12faa20163604d4e3ac83d74bd62343527c19d02d6bd7": "0x2cad71e04bcb4b291ee2c07deb5949371de1e15c0f0fe33b0d33ed63e8b10e44" - }, - "Test_TokenAllowlist": { - "0x118b2f9b3657928d5b1848fade0ddc48dd50e9d65e683a363b653266870adaee": "0xb6e8c3e0c43f2d7cd25266fd1e3cd9786498c1ede5ecee6e2268a67fef120171", - "0x29e11e7edb0660ff55bd297aef1d1ad44c2a00eaee4c1dac7b9e5c9e5b85938e": "0x71d050b4c6e3a8f6e08c4c3886501335a1f44639031433cec645b8da7305360f" - }, - "Test_UniswapV2DirectToLiquidity": { - "0x5648c9130a68e793e493c9f775617f4ebbff10e547a9e1cb15b43d61c8abc86e": "0x9d2b4c2da97b7ffe6d1b131380d95223b2eeaa53b474ba4d439c86faa1168114" - }, - "Test_UniswapV2Router": { - "0x82202d1015ce048c53cd194a4407a02c152ee834d4b503f3dbd41d3799ee0dbb": "0x67226a40a6c0b7968e2cf7c37240a16ea7f3deb588c2421d67ce10cb4494de7e" - }, - "Test_UniswapV3DirectToLiquidity": { - "0xd035f617c30775f0b66153027385d2fa109fa60e886f4b20d8de7d431bd64a78": "0x8a98b0c781361bd4e55135c6abb2d3acb524033c20f425b96b4f8aeec5512a69" - }, - "Test_UniswapV3Factory": { - "0xd7d7fb682911c91b7e7df5ed01ce4da341bd2c8827fcbe2194bb528657a2984d": "0x37651652ec1265bc6df5f5abf562bdaec8f7d4a45df23c214f03ff9418ed4be7" - }, "TokenAllowlist": { "0x09db47d395a68db033a3b222b9d1a212cec8422b03aeafc313aa4d2813c6dd60": "0xe07a005213f35e1f050a4da040d6bc3cae2ad333647b51a6ffa2e7941980043a", "0x30d8cf89cc8c815884740dc27e72a1f8b5dacbbe39f3d1e35deb436176390b20": "0xaa12d3f9826fbc3d54f789bfc36030a3dfe0ea0a538d4968716e10eecc2b91b2", From 91a619946c575ad0380f6c8d1cc5dc47079ae761 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:37:15 +0400 Subject: [PATCH 15/19] Remove obsolete docs --- README.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/README.md b/README.md index 8cfbe85b..9ad85e45 100644 --- a/README.md +++ b/README.md @@ -26,17 +26,6 @@ The test suite can be run with: pnpm run test ``` -#### Address Mismatch - -Many of the contracts (e.g. callbacks) require a specific address prefix or have a deterministic address. If tests are failing for this reason, the cause is usually one of: - -- The code of a callback contract has been changed - - This requires re-generating the salt for the contract. See the [test_salts.sh](/script/salts/test/test_salts.sh) script. -- There has been a change to the dependencies under `/lib`. The dependencies affect the build output, so any changes will affect the bytecode generated by the Solidity compiler. - - If the submodule change was inadvertent, this can be fixed by running `pnpm install` to reset the changes. - - In some cases, such as the `g-uni-v1-core` dependency, installing npm packages will result in the remappings being changed. It is best to remove the dependency's respective dependencies in order to fix this. - - If the change to dependencies and invalidation of salts is expected, then new salts must be generated. In some cases (such as Uniswap V2 and V3 factories), the new addresses must be recorded in the `Constants.sol` file. - ### Format Combines `forge fmt` and `solhint` From 18ef1443507d6983e2473161a7da1b9a2721bf0c Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:41:46 +0400 Subject: [PATCH 16/19] Create the bytecode directory --- script/salts/WithSalts.s.sol | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/script/salts/WithSalts.s.sol b/script/salts/WithSalts.s.sol index 52e6fcae..cc706cbf 100644 --- a/script/salts/WithSalts.s.sol +++ b/script/salts/WithSalts.s.sol @@ -28,13 +28,7 @@ contract WithSalts is Script { function _createBytecodeDirectory() internal { // Create the bytecode folder if it doesn't exist if (!vm.isDir(_getBytecodeDirectory())) { - console2.log("Creating bytecode directory"); - - string[] memory inputs = new string[](2); - inputs[0] = "mkdir"; - inputs[1] = _BYTECODE_DIR; - - vm.ffi(inputs); + vm.createDir(_getBytecodeDirectory(), true); } } @@ -55,6 +49,7 @@ contract WithSalts is Script { return (bytecodePath, bytecodeHash); } + _createBytecodeDirectory(); vm.writeFile(bytecodePath, vm.toString(bytecode)); return (bytecodePath, bytecodeHash); From 2055e473f029cf02b2336257022e035301bf40d7 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Tue, 4 Mar 2025 22:45:08 +0400 Subject: [PATCH 17/19] Use foundry stable --- .github/workflows/test.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 125dd02c..db5c1adc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,8 +33,6 @@ jobs: - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 - with: - version: nightly # Providing the SSH key to the checkout action does not work with our config. # It likely is because of the install script wiping the lib/ directory. From b24ff8041fdd1052b760a7cfca6c5d08b82b7011 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Wed, 5 Mar 2025 22:18:12 +0400 Subject: [PATCH 18/19] Remove Baseline code instead of commenting-out --- .gitmodules | 3 - script/deploy/Deploy.s.sol | 319 ----- .../baselineAllocatedAllowlist-sample.json | 13 - script/install.sh | 8 +- script/patch/baseline.patch | 139 --- script/patch/baseline.sh | 9 - script/salts/README.md | 41 - script/salts/dtl-baseline/BaselineSalts.s.sol | 172 --- script/salts/dtl-baseline/baseline_salts.sh | 49 - script/salts/test/TestSalts.s.sol | 117 -- script/salts/test/test_salts.sh | 54 - .../BaselineV2/BALwithAllocatedAllowlist.sol | 184 --- .../liquidity/BaselineV2/BALwithAllowlist.sol | 156 --- .../BaselineV2/BALwithCappedAllowlist.sol | 101 -- .../BaselineV2/BALwithTokenAllowlist.sol | 133 -- .../BaselineV2/BaselineAxisLaunch.sol | 962 --------------- src/callbacks/liquidity/BaselineV2/README.md | 46 - .../liquidity/BaselineV2/lib/IBPOOL.sol | 127 -- .../liquidity/BaselineV2/lib/ICREDT.sol | 63 - .../liquidity/BaselineV2/lib/ILOOPS.sol | 8 - .../liquidity/BaselineV2/lib/Kernel.sol | 438 ------- test/Constants.sol | 3 - .../BaselineAllocatedAllowlistTest.sol | 48 - .../BaselineV2/AllocatedAllowlist/onBid.t.sol | 248 ---- .../AllocatedAllowlist/onCreate.t.sol | 69 -- .../AllocatedAllowlist/setMerkleRoot.t.sol | 101 -- .../Allowlist/BaselineAllowlistTest.sol | 48 - .../BaselineV2/Allowlist/onBid.t.sol | 123 -- .../BaselineV2/Allowlist/onCreate.t.sol | 69 -- .../BaselineV2/Allowlist/setMerkleRoot.t.sol | 97 -- .../liquidity/BaselineV2/BPOOLMinter.sol | 61 - .../BaselineV2/BaselineAxisLaunchTest.sol | 762 ------------ .../BaselineCappedAllowlistTest.sol | 47 - .../BaselineV2/CappedAllowlist/onBid.t.sol | 211 ---- .../BaselineV2/CappedAllowlist/onCreate.t.sol | 89 -- .../CappedAllowlist/setMerkleRoot.t.sol | 101 -- .../liquidity/BaselineV2/MockBlast.sol | 12 - .../BaselineTokenAllowlistTest.sol | 61 - .../BaselineV2/TokenAllowlist/onBid.t.sol | 75 -- .../BaselineV2/TokenAllowlist/onCreate.t.sol | 108 -- .../liquidity/BaselineV2/onCancel.t.sol | 142 --- .../liquidity/BaselineV2/onCreate.t.sol | 13 - .../liquidity/BaselineV2/onCurate.t.sol | 93 -- .../liquidity/BaselineV2/onSettle.t.sol | 1098 ----------------- .../liquidity/BaselineV2/slide.t.sol | 104 -- .../liquidity/BaselineV2/sweep.t.sol | 93 -- test/invariant/AxisInvariant.sol | 9 - test/invariant/Setup.sol | 125 -- .../invariant/handlers/BaselineDTLHandler.sol | 461 ------- .../handlers/BaselinePoolHandler.sol | 81 -- test/invariant/helpers/BeforeAfter.sol | 14 - test/invariant/helpers/GuardianTester.sol | 25 +- test/invariant/modules/BPOOLMinter.sol | 39 - test/invariant/modules/CREDTMinter.sol | 23 - test/invariant/modules/ModuleTester.sol | 89 -- 55 files changed, 2 insertions(+), 7882 deletions(-) delete mode 100644 script/deploy/sequences/baselineAllocatedAllowlist-sample.json delete mode 100644 script/patch/baseline.patch delete mode 100755 script/patch/baseline.sh delete mode 100644 script/salts/dtl-baseline/BaselineSalts.s.sol delete mode 100755 script/salts/dtl-baseline/baseline_salts.sh delete mode 100644 script/salts/test/TestSalts.s.sol delete mode 100755 script/salts/test/test_salts.sh delete mode 100644 src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/README.md delete mode 100644 src/callbacks/liquidity/BaselineV2/lib/IBPOOL.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/lib/ICREDT.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/lib/ILOOPS.sol delete mode 100644 src/callbacks/liquidity/BaselineV2/lib/Kernel.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/MockBlast.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/onCancel.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/onCreate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/onCurate.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/onSettle.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/slide.t.sol delete mode 100644 test/callbacks/liquidity/BaselineV2/sweep.t.sol delete mode 100644 test/invariant/handlers/BaselineDTLHandler.sol delete mode 100644 test/invariant/handlers/BaselinePoolHandler.sol delete mode 100644 test/invariant/modules/BPOOLMinter.sol delete mode 100644 test/invariant/modules/CREDTMinter.sol delete mode 100644 test/invariant/modules/ModuleTester.sol diff --git a/.gitmodules b/.gitmodules index 6b2efaaf..e69de29b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +0,0 @@ -# [submodule "lib/baseline-v2"] -# path = lib/baseline-v2 -# url = git@github.com:0xBaseline/baseline-v2.git diff --git a/script/deploy/Deploy.s.sol b/script/deploy/Deploy.s.sol index ea5b4ac8..fad95d83 100644 --- a/script/deploy/Deploy.s.sol +++ b/script/deploy/Deploy.s.sol @@ -26,20 +26,6 @@ import {CappedMerkleAllowlist} from "../../src/callbacks/allowlists/CappedMerkle import {MerkleAllowlist} from "../../src/callbacks/allowlists/MerkleAllowlist.sol"; import {TokenAllowlist} from "../../src/callbacks/allowlists/TokenAllowlist.sol"; import {AllocatedMerkleAllowlist} from "../../src/callbacks/allowlists/AllocatedMerkleAllowlist.sol"; -// import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -// import {BALwithAllowlist} from "../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; -// import {BALwithAllocatedAllowlist} from -// "../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; -// import {BALwithCappedAllowlist} from -// "../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -// import {BALwithTokenAllowlist} from -// "../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; - -// Baseline -// import { -// Kernel as BaselineKernel, -// Actions as BaselineKernelActions -// } from "../../src/callbacks/liquidity/BaselineV2/lib/Kernel.sol"; /// @notice Declarative deployment script that reads a deployment sequence (with constructor args) /// and a configured environment file to deploy and install contracts in the Axis protocol. @@ -787,311 +773,6 @@ contract Deploy is Script, WithDeploySequence, WithSalts { return (address(cbBatchAllocatedMerkleAllowlist), _PREFIX_CALLBACKS, deploymentKey); } - // function deployBatchBaselineAxisLaunch( - // string memory sequenceName_ - // ) public returns (address, string memory, string memory) { - // console2.log(""); - // console2.log("Deploying BaselineAxisLaunch (Batch)"); - - // // Get configuration variables - // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - // console2.log(" baselineKernel:", baselineKernel); - // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - // console2.log(" baselineOwner:", baselineOwner); - // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - // console2.log(" reserveToken:", reserveToken); - // string memory deploymentKey = _getDeploymentKey(sequenceName_); - // console2.log(" deploymentKey:", deploymentKey); - - // // Validate arguments - // require(baselineKernel != address(0), "baselineKernel not set"); - // require(baselineOwner != address(0), "baselineOwner not set"); - // require(reserveToken != address(0), "reserveToken not set"); - - // // Get the salt - // // This supports an arbitrary salt key, which can be set in the deployment sequence - // // This is required as each callback is single-use - // bytes32 salt_ = _getSalt( - // deploymentKey, - // type(BaselineAxisLaunch).creationCode, - // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - // ); - - // // Revert if the salt is not set - // require(salt_ != bytes32(0), "Salt not set"); - - // // Deploy the module - // console2.log(" salt:", vm.toString(salt_)); - - // vm.broadcast(); - // BaselineAxisLaunch batchCallback = new BaselineAxisLaunch{salt: salt_}( - // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - // ); - // console2.log(""); - // console2.log(" deployed at:", address(batchCallback)); - - // // If the deployer is the executor, - // // install the module as a policy in the Baseline kernel - // BaselineKernel kernel = BaselineKernel(baselineKernel); - // if (kernel.executor() == msg.sender) { - // vm.broadcast(); - // BaselineKernel(baselineKernel).executeAction( - // BaselineKernelActions.ActivatePolicy, address(batchCallback) - // ); - - // console2.log(" Policy activated in Baseline Kernel"); - // } else { - // console2.log(" Policy activation skipped"); - // } - - // return (address(batchCallback), _PREFIX_CALLBACKS, deploymentKey); - // } - - // function deployBatchBaselineAllocatedAllowlist( - // string memory sequenceName_ - // ) public returns (address, string memory, string memory) { - // console2.log(""); - // console2.log("Deploying BaselineAllocatedAllowlist (Batch)"); - - // // Get configuration variables - // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - // console2.log(" baselineKernel:", baselineKernel); - // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - // console2.log(" baselineOwner:", baselineOwner); - // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - // console2.log(" reserveToken:", reserveToken); - // string memory deploymentKey = _getDeploymentKey(sequenceName_); - // console2.log(" deploymentKey:", deploymentKey); - - // // Validate arguments - // require(baselineKernel != address(0), "baselineKernel not set"); - // require(baselineOwner != address(0), "baselineOwner not set"); - // require(reserveToken != address(0), "reserveToken not set"); - - // // Get the salt - // // This supports an arbitrary salt key, which can be set in the deployment sequence - // // This is required as each callback is single-use - // bytes32 salt_ = _getSalt( - // deploymentKey, - // type(BALwithAllocatedAllowlist).creationCode, - // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - // ); - - // // Revert if the salt is not set - // require(salt_ != bytes32(0), "Salt not set"); - - // // Deploy the module - // console2.log(" salt:", vm.toString(salt_)); - - // vm.broadcast(); - // BALwithAllocatedAllowlist batchAllowlist = new BALwithAllocatedAllowlist{salt: salt_}( - // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - // ); - // console2.log(""); - // console2.log(" deployed at:", address(batchAllowlist)); - - // // If the deployer is the executor, - // // install the module as a policy in the Baseline kernel - // BaselineKernel kernel = BaselineKernel(baselineKernel); - // if (kernel.executor() == msg.sender) { - // vm.broadcast(); - // BaselineKernel(baselineKernel).executeAction( - // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - // ); - - // console2.log(" Policy activated in Baseline Kernel"); - // } else { - // console2.log(" Policy activation skipped"); - // } - - // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - // } - - // function deployBatchBaselineAllowlist( - // string memory sequenceName_ - // ) public returns (address, string memory, string memory) { - // console2.log(""); - // console2.log("Deploying BaselineAllowlist (Batch)"); - - // // Get configuration variables - // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - // console2.log(" baselineKernel:", baselineKernel); - // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - // console2.log(" baselineOwner:", baselineOwner); - // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - // console2.log(" reserveToken:", reserveToken); - // string memory deploymentKey = _getDeploymentKey(sequenceName_); - // console2.log(" deploymentKey:", deploymentKey); - - // // Validate arguments - // require(baselineKernel != address(0), "baselineKernel not set"); - // require(baselineOwner != address(0), "baselineOwner not set"); - // require(reserveToken != address(0), "reserveToken not set"); - - // // Get the salt - // // This supports an arbitrary salt key, which can be set in the deployment sequence - // // This is required as each callback is single-use - // bytes32 salt_ = _getSalt( - // deploymentKey, - // type(BALwithAllowlist).creationCode, - // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - // ); - - // // Revert if the salt is not set - // require(salt_ != bytes32(0), "Salt not set"); - - // // Deploy the module - // console2.log(" salt:", vm.toString(salt_)); - - // vm.broadcast(); - // BALwithAllowlist batchAllowlist = new BALwithAllowlist{salt: salt_}( - // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - // ); - // console2.log(""); - // console2.log(" deployed at:", address(batchAllowlist)); - - // // If the deployer is the executor, - // // install the module as a policy in the Baseline kernel - // BaselineKernel kernel = BaselineKernel(baselineKernel); - // if (kernel.executor() == msg.sender) { - // vm.broadcast(); - // BaselineKernel(baselineKernel).executeAction( - // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - // ); - - // console2.log(" Policy activated in Baseline Kernel"); - // } else { - // console2.log(" Policy activation skipped"); - // } - - // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - // } - - // function deployBatchBaselineCappedAllowlist( - // string memory sequenceName_ - // ) public returns (address, string memory, string memory) { - // console2.log(""); - // console2.log("Deploying BaselineCappedAllowlist (Batch)"); - - // // Get configuration variables - // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - // console2.log(" baselineKernel:", baselineKernel); - // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - // console2.log(" baselineOwner:", baselineOwner); - // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - // console2.log(" reserveToken:", reserveToken); - // string memory deploymentKey = _getDeploymentKey(sequenceName_); - // console2.log(" deploymentKey:", deploymentKey); - - // // Validate arguments - // require(baselineKernel != address(0), "baselineKernel not set"); - // require(baselineOwner != address(0), "baselineOwner not set"); - // require(reserveToken != address(0), "reserveToken not set"); - - // // Get the salt - // // This supports an arbitrary salt key, which can be set in the deployment sequence - // // This is required as each callback is single-use - // bytes32 salt_ = _getSalt( - // deploymentKey, - // type(BALwithCappedAllowlist).creationCode, - // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - // ); - - // // Revert if the salt is not set - // require(salt_ != bytes32(0), "Salt not set"); - - // // Deploy the module - // console2.log(" salt:", vm.toString(salt_)); - - // vm.broadcast(); - // BALwithCappedAllowlist batchAllowlist = new BALwithCappedAllowlist{salt: salt_}( - // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - // ); - // console2.log(""); - // console2.log(" deployed at:", address(batchAllowlist)); - - // // If the deployer is the executor, - // // install the module as a policy in the Baseline kernel - // BaselineKernel kernel = BaselineKernel(baselineKernel); - // if (kernel.executor() == msg.sender) { - // vm.broadcast(); - // BaselineKernel(baselineKernel).executeAction( - // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - // ); - - // console2.log(" Policy activated in Baseline Kernel"); - // } else { - // console2.log(" Policy activation skipped"); - // } - - // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - // } - - // function deployBatchBaselineTokenAllowlist( - // string memory sequenceName_ - // ) public returns (address, string memory, string memory) { - // console2.log(""); - // console2.log("Deploying BaselineTokenAllowlist (Batch)"); - - // // Get configuration variables - // address batchAuctionHouse = _getAddressNotZero("deployments.BatchAuctionHouse"); - // address baselineKernel = _getSequenceAddress(sequenceName_, "args.baselineKernel"); - // console2.log(" baselineKernel:", baselineKernel); - // address baselineOwner = _getSequenceAddress(sequenceName_, "args.baselineOwner"); - // console2.log(" baselineOwner:", baselineOwner); - // address reserveToken = _getSequenceAddress(sequenceName_, "args.reserveToken"); - // console2.log(" reserveToken:", reserveToken); - // string memory deploymentKey = _getDeploymentKey(sequenceName_); - // console2.log(" deploymentKey:", deploymentKey); - - // // Validate arguments - // require(baselineKernel != address(0), "baselineKernel not set"); - // require(baselineOwner != address(0), "baselineOwner not set"); - // require(reserveToken != address(0), "reserveToken not set"); - - // // Get the salt - // // This supports an arbitrary salt key, which can be set in the deployment sequence - // // This is required as each callback is single-use - // bytes32 salt_ = _getSalt( - // deploymentKey, - // type(BALwithTokenAllowlist).creationCode, - // abi.encode(batchAuctionHouse, baselineKernel, reserveToken, baselineOwner) - // ); - - // // Revert if the salt is not set - // require(salt_ != bytes32(0), "Salt not set"); - - // // Deploy the module - // console2.log(" salt:", vm.toString(salt_)); - - // vm.broadcast(); - // BALwithTokenAllowlist batchAllowlist = new BALwithTokenAllowlist{salt: salt_}( - // batchAuctionHouse, baselineKernel, reserveToken, baselineOwner - // ); - // console2.log(""); - // console2.log(" deployed at:", address(batchAllowlist)); - - // // If the deployer is the executor, - // // install the module as a policy in the Baseline kernel - // BaselineKernel kernel = BaselineKernel(baselineKernel); - // if (kernel.executor() == msg.sender) { - // vm.broadcast(); - // BaselineKernel(baselineKernel).executeAction( - // BaselineKernelActions.ActivatePolicy, address(batchAllowlist) - // ); - - // console2.log(" Policy activated in Baseline Kernel"); - // } else { - // console2.log(" Policy activation skipped"); - // } - - // return (address(batchAllowlist), _PREFIX_CALLBACKS, deploymentKey); - // } - // ========== HELPER FUNCTIONS ========== // function _configureDeployment(string memory data_, string memory name_) internal { diff --git a/script/deploy/sequences/baselineAllocatedAllowlist-sample.json b/script/deploy/sequences/baselineAllocatedAllowlist-sample.json deleted file mode 100644 index 49f34d3f..00000000 --- a/script/deploy/sequences/baselineAllocatedAllowlist-sample.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "sequence": [ - { - "name": "BatchBaselineAllocatedAllowlist", - "deploymentKeySuffix": "Sample", - "args": { - "baselineKernel": "0x0000000000000000000000000000000000000001", - "baselineOwner": "0xB47C8e4bEb28af80eDe5E5bF474927b110Ef2c0e", - "reserveToken": "0x0000000000000000000000000000000000000002" - } - } - ] -} diff --git a/script/install.sh b/script/install.sh index 23b2383b..54ee8861 100755 --- a/script/install.sh +++ b/script/install.sh @@ -20,13 +20,7 @@ echo " Done" echo "" echo "*** Restoring submodule commits" -# echo "" -# echo "baseline" -# cd lib/baseline-v2/ && git checkout 8950018baec27d6497fba409cb361a596535447d && cd ../.. - -# echo "" -# echo "*** Applying patch to Baseline submodule" -# patch -d lib/baseline-v2/ -p1 < script/patch/baseline.patch +# Nothing to do echo "" echo "*** Installing soldeer dependencies" diff --git a/script/patch/baseline.patch b/script/patch/baseline.patch deleted file mode 100644 index 53a2c1cf..00000000 --- a/script/patch/baseline.patch +++ /dev/null @@ -1,139 +0,0 @@ -diff --git a/src/modules/BPOOL.v1.sol b/src/modules/BPOOL.v1.sol -index 82aa5d7..d889bae 100644 ---- a/src/modules/BPOOL.v1.sol -+++ b/src/modules/BPOOL.v1.sol -@@ -1,17 +1,17 @@ - // SPDX-License-Identifier: AGPL-3.0-only - pragma solidity ^0.8.0; - --import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol"; -- --import "src/Kernel.sol"; --import {ERC20} from "solmate/tokens/ERC20.sol"; --import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol"; --import {TickMath} from "v3-core/libraries/TickMath.sol"; --import {FixedPoint96} from "v3-core/libraries/FixedPoint96.sol"; --import {IUniswapV3Pool} from "v3-core/interfaces/IUniswapV3Pool.sol"; --import {IUniswapV3Factory} from "v3-core/interfaces/IUniswapV3Factory.sol"; --import {LiquidityAmounts} from "v3-periphery/libraries/LiquidityAmounts.sol"; --import {BlastClaimer} from "src/utils/BlastClaimer.sol"; -+import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; -+ -+import {Kernel, Module, Keycode, toKeycode} from "../Kernel.sol"; -+import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; -+import {SafeTransferLib} from "@solmate-6.8.0/utils/SafeTransferLib.sol"; -+import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; -+import {FixedPoint96} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/FixedPoint96.sol"; -+import {IUniswapV3Pool} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Pool.sol"; -+import {IUniswapV3Factory} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Factory.sol"; -+import {LiquidityAmounts} from "@uniswap-v3-periphery-1.4.2-solc-0.8/libraries/LiquidityAmounts.sol"; -+import {BlastClaimer} from "../utils/BlastClaimer.sol"; - - - // Liquidity range -diff --git a/src/modules/CREDT.v1.sol b/src/modules/CREDT.v1.sol -index 2afa1c3..e920452 100644 ---- a/src/modules/CREDT.v1.sol -+++ b/src/modules/CREDT.v1.sol -@@ -1,11 +1,11 @@ - // SPDX-License-Identifier: MIT --pragma solidity ^0.8.23; -+pragma solidity ^0.8.19; - --import {ERC20} from "solmate/tokens/ERC20.sol"; -+import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; - --import "src/Kernel.sol"; --import {TimeslotLib} from "src/utils/TimeslotLib.sol"; --import {BlastClaimer} from "src/utils/BlastClaimer.sol"; -+import {Kernel, Module, Keycode, toKeycode} from "../Kernel.sol"; -+import {TimeslotLib} from "../utils/TimeslotLib.sol"; -+import {BlastClaimer} from "../utils/BlastClaimer.sol"; - - /// @notice Individual credit account information per user - struct CreditAccount { -diff --git a/src/modules/LOOPS.v1.sol b/src/modules/LOOPS.v1.sol -index 0ee6fe1..966c622 100644 ---- a/src/modules/LOOPS.v1.sol -+++ b/src/modules/LOOPS.v1.sol -@@ -1,22 +1,20 @@ - // SPDX-License-Identifier: MIT --pragma solidity ^0.8.23; -+pragma solidity ^0.8.19; - --import {console2} from "forge-std/console2.sol"; -+import {console2} from "@forge-std-1.9.1/console2.sol"; - --import {Owned} from "solmate/auth/Owned.sol"; --import {ERC20} from "solmate/tokens/ERC20.sol"; --import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol"; --import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol"; -+import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; -+import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; -+import {SafeTransferLib} from "@solmate-6.8.0/utils/SafeTransferLib.sol"; -+import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; - --import {FixedPoint96} from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; -+import {FixedPoint96} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/FixedPoint96.sol"; - - // Kernel dependencies --import "src/Kernel.sol"; --import {BPOOLv1, Range, Position, IUniswapV3Pool} from "src/modules/BPOOL.v1.sol"; -+import "../Kernel.sol"; -+import {BPOOLv1, Range, Position, IUniswapV3Pool} from "../modules/BPOOL.v1.sol"; - --import {console2} from "forge-std/console2.sol"; -- --import {BlastClaimer} from "src/utils/BlastClaimer.sol"; -+import {BlastClaimer} from "../utils/BlastClaimer.sol"; - - /// @title LOOPSv1 - -@@ -142,7 +140,7 @@ contract LOOPSv1 is Module { - - bAsset.transfer(msg.sender, collateralRedeemed_); - } -- -+ - function chargeFunding() external permissioned { - _chargeFunding(); - } -diff --git a/src/policies/MarketMaking.sol b/src/policies/MarketMaking.sol -index 4b9eb25..de74542 100644 ---- a/src/policies/MarketMaking.sol -+++ b/src/policies/MarketMaking.sol -@@ -1,20 +1,20 @@ - // SPDX-Identifier: AGPL-3.0-only - pragma solidity ^0.8.0; - --import {Owned} from "solmate/auth/Owned.sol"; --import {ERC20} from "solmate/tokens/ERC20.sol"; --import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol"; --import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol"; --import {LiquidityAmounts} from "v3-periphery/libraries/LiquidityAmounts.sol"; -- --import {TickMath} from "v3-core/libraries/TickMath.sol"; --import {FixedPoint96} from "v3-core/libraries/FixedPoint96.sol"; -- --import "src/Kernel.sol"; --import {BPOOLv1, Range, Ticks, Position, IUniswapV3Pool} from "src/modules/BPOOL.v1.sol"; --import {CREDTv1} from "src/modules/CREDT.v1.sol"; --import {LOOPSv1} from "src/modules/LOOPS.v1.sol"; --import {BlastClaimer} from "src/utils/BlastClaimer.sol"; -+import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; -+import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; -+import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; -+import {SafeTransferLib} from "@solmate-6.8.0/utils/SafeTransferLib.sol"; -+import {LiquidityAmounts} from "@uniswap-v3-periphery-1.4.2-solc-0.8/libraries/LiquidityAmounts.sol"; -+ -+import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; -+import {FixedPoint96} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/FixedPoint96.sol"; -+ -+import "../Kernel.sol"; -+import {BPOOLv1, Range, Ticks, Position, IUniswapV3Pool} from "../modules/BPOOL.v1.sol"; -+import {CREDTv1} from "../modules/CREDT.v1.sol"; -+import {LOOPSv1} from "../modules/LOOPS.v1.sol"; -+import {BlastClaimer} from "../utils/BlastClaimer.sol"; - - import {console2} from "forge-std/console2.sol"; - diff --git a/script/patch/baseline.sh b/script/patch/baseline.sh deleted file mode 100755 index 83f63b2d..00000000 --- a/script/patch/baseline.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -# Move into the right directory -cd lib/baseline-v2 - -# Generate the diff -git diff . > ../../script/patch/baseline.patch - -echo "Done!" diff --git a/script/salts/README.md b/script/salts/README.md index a40f6b69..8737148f 100644 --- a/script/salts/README.md +++ b/script/salts/README.md @@ -4,47 +4,6 @@ This document provides instructions on how to generate and use salts for CREATE2 ## Tasks -### Generating Test Salts - -Many of the tests use salts to deploy callbacks at addresses with a specific prefix. Changes to the state variables in the test contract can require the re-generation of the salt. To do so, perform the following: - -```bash -./script/salts/test/test_salts.sh --saltKey -``` - -For example, if re-generating salts for the `CappedMerkleAllowlist` contract, make the following call: - -```bash -./script/salts/test/test_salts.sh --saltKey CappedMerkleAllowlist -``` - -The resulting salts will be written to the `./script/salts/salts.json` file, which the test cases will read from. - -Notes: - -- When re-generating salts, ensure that any git submodule changes are either reverted or committed. For example, if switching from a branch with a particular submodule to a branch in which that submodule is not present, the submodule changes will not be automatically reverted. This will cause changes in the generated bytecode and in turn, the salt. The submodule changes must be reverted and the salts generated afterwards. - -### Generating Salts for Baseline Allocated Allowlist - -The Baseline Allocated Allowlist is a single-use Callbacks contract that enables the owner of a fixed-price batch auction to: - -- deploy the proceeds using Baseline -- specify a bid limit for each address - -To generate a salt for a specific callback deployment, the following addresses are needed: - -- Baseline kernel -- Owner of the Baseline deployment (which will have the ability to withdraw reserves) -- Reserve (quote) token - -These addresses are pulled from the deployment sequence file. - -The following script can then be run: - -```bash -./script/salts/dtl-baseline/baseline_salts.sh --deployFile -``` - ### Generating Salts for Uniswap Direct to Liquidity The following command will generate salts for any Uniswap DTL callbacks in the specified deployment sequence file: diff --git a/script/salts/dtl-baseline/BaselineSalts.s.sol b/script/salts/dtl-baseline/BaselineSalts.s.sol deleted file mode 100644 index ea72c095..00000000 --- a/script/salts/dtl-baseline/BaselineSalts.s.sol +++ /dev/null @@ -1,172 +0,0 @@ -/// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Scripting libraries -import {Script, console2} from "@forge-std-1.9.1/Script.sol"; -import {WithSalts} from "../WithSalts.s.sol"; -import {WithDeploySequence} from "../../deploy/WithDeploySequence.s.sol"; - -import {BaselineAxisLaunch} from - "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {BALwithAllocatedAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; -import {BALwithAllowlist} from "../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; -import {BALwithCappedAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -import {BALwithTokenAllowlist} from - "../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; - -contract BaselineSalts is Script, WithDeploySequence, WithSalts { - string internal constant _ADDRESS_PREFIX = "EF"; - - address internal _envBatchAuctionHouse; - - function _setUp(string calldata chain_, string calldata sequenceFilePath_) internal { - _loadSequence(chain_, sequenceFilePath_); - _createBytecodeDirectory(); - - // Cache auction houses - _envBatchAuctionHouse = _envAddressNotZero("deployments.BatchAuctionHouse"); - } - - function generate(string calldata chain_, string calldata deployFilePath_) public { - _setUp(chain_, deployFilePath_); - - // Iterate over the deployment sequence - string[] memory sequenceNames = _getSequenceNames(); - for (uint256 i; i < sequenceNames.length; i++) { - string memory sequenceName = sequenceNames[i]; - console2.log(""); - console2.log("Generating salt for :", sequenceName); - - string memory deploymentKey = _getDeploymentKey(sequenceName); - console2.log(" deploymentKey: %s", deploymentKey); - - // BaselineAxisLaunch - if ( - keccak256(abi.encodePacked(sequenceName)) - == keccak256(abi.encodePacked("BatchBaselineAxisLaunch")) - ) { - _generateBaselineAxisLaunch(sequenceName, deploymentKey); - } - // BaselineAllocatedAllowlist - else if ( - keccak256(abi.encodePacked(sequenceName)) - == keccak256(abi.encodePacked("BatchBaselineAllocatedAllowlist")) - ) { - _generateBaselineAllocatedAllowlist(sequenceName, deploymentKey); - } - // BaselineAllowlist - else if ( - keccak256(abi.encodePacked(sequenceName)) - == keccak256(abi.encodePacked("BatchBaselineAllowlist")) - ) { - _generateBaselineAllowlist(sequenceName, deploymentKey); - } - // BaselineCappedAllowlist - else if ( - keccak256(abi.encodePacked(sequenceName)) - == keccak256(abi.encodePacked("BatchBaselineCappedAllowlist")) - ) { - _generateBaselineCappedAllowlist(sequenceName, deploymentKey); - } - // BaselineTokenAllowlist - else if ( - keccak256(abi.encodePacked(sequenceName)) - == keccak256(abi.encodePacked("BatchBaselineTokenAllowlist")) - ) { - _generateBaselineTokenAllowlist(sequenceName, deploymentKey); - } - // Something else - else { - console2.log(" Skipping unknown sequence: %s", sequenceName); - } - } - } - - function _generateBaselineAxisLaunch( - string memory sequenceName_, - string memory deploymentKey_ - ) internal { - bytes memory contractCode = type(BaselineAxisLaunch).creationCode; - bytes memory contractArgs_ = abi.encode( - _envBatchAuctionHouse, - _getSequenceAddress(sequenceName_, "args.baselineKernel"), - _getSequenceAddress(sequenceName_, "args.reserveToken"), - _getSequenceAddress(sequenceName_, "args.baselineOwner") - ); - - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(deploymentKey_, contractCode, contractArgs_); - _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); - } - - function _generateBaselineAllocatedAllowlist( - string memory sequenceName_, - string memory deploymentKey_ - ) internal { - bytes memory contractCode = type(BALwithAllocatedAllowlist).creationCode; - bytes memory contractArgs_ = abi.encode( - _envBatchAuctionHouse, - _getSequenceAddress(sequenceName_, "args.baselineKernel"), - _getSequenceAddress(sequenceName_, "args.reserveToken"), - _getSequenceAddress(sequenceName_, "args.baselineOwner") - ); - - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(deploymentKey_, contractCode, contractArgs_); - _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); - } - - function _generateBaselineAllowlist( - string memory sequenceName_, - string memory deploymentKey_ - ) internal { - bytes memory contractCode = type(BALwithAllowlist).creationCode; - bytes memory contractArgs_ = abi.encode( - _envBatchAuctionHouse, - _getSequenceAddress(sequenceName_, "args.baselineKernel"), - _getSequenceAddress(sequenceName_, "args.reserveToken"), - _getSequenceAddress(sequenceName_, "args.baselineOwner") - ); - - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(deploymentKey_, contractCode, contractArgs_); - _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); - } - - function _generateBaselineCappedAllowlist( - string memory sequenceName_, - string memory deploymentKey_ - ) internal { - bytes memory contractCode = type(BALwithCappedAllowlist).creationCode; - bytes memory contractArgs_ = abi.encode( - _envBatchAuctionHouse, - _getSequenceAddress(sequenceName_, "args.baselineKernel"), - _getSequenceAddress(sequenceName_, "args.reserveToken"), - _getSequenceAddress(sequenceName_, "args.baselineOwner") - ); - - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(deploymentKey_, contractCode, contractArgs_); - _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); - } - - function _generateBaselineTokenAllowlist( - string memory sequenceName_, - string memory deploymentKey_ - ) internal { - bytes memory contractCode = type(BALwithTokenAllowlist).creationCode; - bytes memory contractArgs_ = abi.encode( - _envBatchAuctionHouse, - _getSequenceAddress(sequenceName_, "args.baselineKernel"), - _getSequenceAddress(sequenceName_, "args.reserveToken"), - _getSequenceAddress(sequenceName_, "args.baselineOwner") - ); - - (string memory bytecodePath, bytes32 bytecodeHash) = - _writeBytecode(deploymentKey_, contractCode, contractArgs_); - _setSalt(bytecodePath, _ADDRESS_PREFIX, deploymentKey_, bytecodeHash); - } -} -*/ diff --git a/script/salts/dtl-baseline/baseline_salts.sh b/script/salts/dtl-baseline/baseline_salts.sh deleted file mode 100755 index 94378961..00000000 --- a/script/salts/dtl-baseline/baseline_salts.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash - -# Usage: -# ./baseline_salts.sh --deployFile --envFile <.env> -# -# Expects the following environment variables: -# CHAIN: The chain to deploy to, based on values from the ./script/env.json file. - -# Iterate through named arguments -# Source: https://unix.stackexchange.com/a/388038 -while [ $# -gt 0 ]; do - if [[ $1 == *"--"* ]]; then - v="${1/--/}" - declare $v="$2" - fi - - shift -done - -DEPLOY_FILE=$deployFile - -# Get the name of the .env file or use the default -ENV_FILE=${envFile:-".env"} -echo "Sourcing environment variables from $ENV_FILE" - -# Load environment file -set -a # Automatically export all variables -source $ENV_FILE -set +a # Disable automatic export - -# Check that the CHAIN environment variable is set -if [ -z "$CHAIN" ] -then - echo "CHAIN environment variable is not set. Please set it in the .env file or provide it as an environment variable." - exit 1 -fi - -# Check if DEPLOY_FILE is set -if [ -z "$DEPLOY_FILE" ] -then - echo "No deploy file specified. Provide the relative path after the --deployFile flag." - exit 1 -fi - -echo "Using chain: $CHAIN" -echo "Using RPC at URL: $RPC_URL" -echo "Using deploy file: $DEPLOY_FILE" - -forge script ./script/salts/dtl-baseline/BaselineSalts.s.sol:BaselineSalts --sig "generate(string,string)()" $CHAIN $DEPLOY_FILE diff --git a/script/salts/test/TestSalts.s.sol b/script/salts/test/TestSalts.s.sol deleted file mode 100644 index cfe1210f..00000000 --- a/script/salts/test/TestSalts.s.sol +++ /dev/null @@ -1,117 +0,0 @@ -/// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; - -// Scripting libraries -import {Script} from "@forge-std-1.9.1/Script.sol"; -import {console2} from "@forge-std-1.9.1/console2.sol"; -import {WithEnvironment} from "../../deploy/WithEnvironment.s.sol"; -import {WithSalts} from "../WithSalts.s.sol"; -import {TestConstants} from "../../../test/Constants.sol"; - -// Libraries -import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; -import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; - -// import {BaselineAxisLaunch} from -// "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -// import {BALwithAllocatedAllowlist} from -// "../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; -// import {BALwithAllowlist} from "../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; -// import {BALwithCappedAllowlist} from -// "../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -// import {BALwithTokenAllowlist} from -// "../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; - -contract TestSalts is Script, WithEnvironment, Permit2User, WithSalts, TestConstants { - string internal constant _CAPPED_MERKLE_ALLOWLIST = "CappedMerkleAllowlist"; - string internal constant _ALLOCATED_MERKLE_ALLOWLIST = "AllocatedMerkleAllowlist"; - string internal constant _TOKEN_ALLOWLIST = "TokenAllowlist"; - - function _setUp( - string calldata chain_ - ) internal { - _loadEnv(chain_); - _createBytecodeDirectory(); - } - - function generate(string calldata chain_, string calldata saltKey_) public { - _setUp(chain_); - - // For the given salt key, call the appropriate selector - // e.g. a salt key named MockCallback would require the following function: generateMockCallback() - bytes4 selector = bytes4(keccak256(bytes(string.concat("generate", saltKey_, "()")))); - - // Call the generate function for the salt key - (bool success,) = address(this).call(abi.encodeWithSelector(selector)); - require(success, string.concat("Failed to generate ", saltKey_)); - } - - // function generateBaselineQuoteToken() public { - // // Generate a salt for a MockERC20 quote token - // bytes memory qtArgs = abi.encode("Quote Token", "QT", 18); - // bytes memory qtContractCode = type(MockERC20).creationCode; - // (string memory qtBytecodePath, bytes32 qtBytecodeHash) = - // _writeBytecode("QuoteToken", qtContractCode, qtArgs); - // _setTestSaltWithDeployer( - // qtBytecodePath, "AA", "QuoteToken", qtBytecodeHash, _CREATE2_DEPLOYER - // ); - - // // Fetch the salt that was set - // bytes32 quoteTokenSalt = _getSalt("Test_QuoteToken", qtContractCode, qtArgs); - - // // Get the address of the quote token - // // Update the `_BASELINE_QUOTE_TOKEN` constants with this value - // vm.prank(_CREATE2_DEPLOYER); - // MockERC20 quoteToken = new MockERC20{salt: quoteTokenSalt}("Quote Token", "QT", 18); - // console2.log("Quote Token address: ", address(quoteToken)); - // } - - // function generateBaselineAxisLaunch() public { - // // Get the salt - // bytes memory callbackArgs = - // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - // "BaselineAxisLaunch", type(BaselineAxisLaunch).creationCode, callbackArgs - // ); - // _setTestSalt(callbackBytecodePath, "EF", "BaselineAxisLaunch", callbackBytecodeHash); - // } - - // function generateBaselineAllocatedAllowlist() public { - // // Get the salt - // bytes memory callbackArgs = - // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - // "BaselineAllocatedAllowlist", type(BALwithAllocatedAllowlist).creationCode, callbackArgs - // ); - // _setTestSalt(callbackBytecodePath, "EF", "BaselineAllocatedAllowlist", callbackBytecodeHash); - // } - - // function generateBaselineAllowlist() public { - // // Get the salt - // bytes memory callbackArgs = - // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = - // _writeBytecode("BaselineAllowlist", type(BALwithAllowlist).creationCode, callbackArgs); - // _setTestSalt(callbackBytecodePath, "EF", "BaselineAllowlist", callbackBytecodeHash); - // } - - // function generateBaselineCappedAllowlist() public { - // // Get the salt - // bytes memory callbackArgs = - // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - // "BaselineCappedAllowlist", type(BALwithCappedAllowlist).creationCode, callbackArgs - // ); - // _setTestSalt(callbackBytecodePath, "EF", "BaselineCappedAllowlist", callbackBytecodeHash); - // } - - // function generateBaselineTokenAllowlist() public { - // // Get the salt - // bytes memory callbackArgs = - // abi.encode(_AUCTION_HOUSE, _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - // (string memory callbackBytecodePath, bytes32 callbackBytecodeHash) = _writeBytecode( - // "BaselineTokenAllowlist", type(BALwithTokenAllowlist).creationCode, callbackArgs - // ); - // _setTestSalt(callbackBytecodePath, "EF", "BaselineTokenAllowlist", callbackBytecodeHash); - // } -} diff --git a/script/salts/test/test_salts.sh b/script/salts/test/test_salts.sh deleted file mode 100755 index f1dacaca..00000000 --- a/script/salts/test/test_salts.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash - -# Usage: -# ./test_salts.sh --saltKey --envFile <.env> - -# Iterate through named arguments -# Source: https://unix.stackexchange.com/a/388038 -while [ $# -gt 0 ]; do - if [[ $1 == *"--"* ]]; then - v="${1/--/}" - declare $v="$2" - fi - - shift -done - -# Get the name of the .env file or use the default -ENV_FILE=${envFile:-".env"} -echo "Sourcing environment variables from $ENV_FILE" - -# Load environment file -set -a # Automatically export all variables -source $ENV_FILE -set +a # Disable automatic export - -# Check that the CHAIN environment variable is set -if [ -z "$CHAIN" ] -then - echo "CHAIN environment variable is not set. Please set it in the .env file or provide it as an environment variable." - exit 1 -fi - -# Check if saltKey is specified -if [ -z "$saltKey" ] -then - echo "No salt key specified. Provide the salt key after the --saltKey flag." - exit 1 -fi - -echo "Using chain: $CHAIN" -echo "Using RPC at URL: $RPC_URL" -echo "Salt key: $saltKey" - -salt_file="./script/salts/salts.json" -salt_tmp_file="./script/salts/salts.json.tmp" - -# Clear the salts for the specified salt key -if [ -f $salt_file ]; then - echo "Clearing old values for salt key: $saltKey" - jq "del(.\"Test_$saltKey\")" $salt_file > $salt_tmp_file && mv $salt_tmp_file $salt_file -fi - -# Generate bytecode -forge script ./script/salts/test/TestSalts.s.sol:TestSalts --sig "generate(string,string)()" $CHAIN $saltKey diff --git a/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol deleted file mode 100644 index 2894f86a..00000000 --- a/src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol +++ /dev/null @@ -1,184 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; - -// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; - -/// @notice Allocated allowlist version of the Baseline Axis Launch callback for batch auctions. -/// @notice This version allows for each address in the Merkle tree to have a per-address amount of quote tokens they can spend. -/// @dev The merkle tree is expected to have both an address and an amount of quote tokens they can spend in each leaf. -// contract BALwithAllocatedAllowlist is BaselineAxisLaunch { -// // ========== ERRORS ========== // - -// /// @notice Error message when the bid amount exceeds the limit assigned to a buyer -// error Callback_ExceedsLimit(); - -// /// @notice Error message when the callback state does not support the action -// error Callback_InvalidState(); - -// // ========== EVENTS ========== // - -// /// @notice Emitted when the merkle root is set -// event MerkleRootSet(bytes32 merkleRoot); - -// // ========== STATE VARIABLES ========== // - -// /// @notice The root of the merkle tree that represents the allowlist -// /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree -// /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. -// bytes32 public merkleRoot; - -// /// @notice Tracks the cumulative amount spent by a buyer -// mapping(address => uint256) public buyerSpent; - -// // ========== CONSTRUCTOR ========== // - -// // PERMISSIONS -// // onCreate: true -// // onCancel: true -// // onCurate: true -// // onPurchase: false -// // onBid: true -// // onSettle: true -// // receiveQuoteTokens: true -// // sendBaseTokens: true -// // Contract prefix should be: 11101111 = 0xEF - -// constructor( -// address auctionHouse_, -// address baselineKernel_, -// address reserve_, -// address owner_ -// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - -// // ========== CALLBACK FUNCTIONS ========== // - -// /// @inheritdoc BaselineAxisLaunch -// /// @dev This function reverts if: -// /// - `allowlistData_` is not of the correct length -// /// -// /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root -// function __onCreate( -// uint96, -// address, -// address, -// address, -// uint256, -// bool, -// bytes memory allowlistData_ -// ) internal virtual override { -// // Check that the parameters are of the correct length -// if (allowlistData_.length != 32) { -// revert Callback_InvalidParams(); -// } - -// // Decode the merkle root from the callback data -// bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); - -// // Set the merkle root and buyer limit -// merkleRoot = merkleRootParams; -// emit MerkleRootSet(merkleRoot); -// } - -// /// @inheritdoc BaselineAxisLaunch -// /// -// /// @param callbackData_ abi-encoded data: (bytes32[], uint256) representing the merkle proof and allocated amount -// function _onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual override { -// // Validate that the buyer is allowed to participate -// uint256 allocatedAmount = _canParticipate(buyer_, callbackData_); - -// // Validate that the buyer can buy the amount -// _canBuy(buyer_, amount_, allocatedAmount); - -// // Call any additional implementation-specific logic -// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); -// } - -// /// @notice Override this function to implement additional functionality for the `onBid` callback -// /// -// /// @param lotId_ The ID of the lot -// /// @param bidId_ The ID of the bid -// /// @param buyer_ The address of the buyer -// /// @param amount_ The amount of quote tokens -// /// @param callbackData_ The callback data -// function __onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual {} - -// // ========== INTERNAL FUNCTIONS ========== // - -// /// @dev The buyer must provide the proof and their total allocated amount in the callback data for this to succeed. -// function _canParticipate( -// address buyer_, -// bytes calldata callbackData_ -// ) internal view returns (uint256) { -// // Decode the merkle proof from the callback data -// (bytes32[] memory proof, uint256 allocatedAmount) = -// abi.decode(callbackData_, (bytes32[], uint256)); - -// // Get the leaf for the buyer -// bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_, allocatedAmount)))); - -// // Validate the merkle proof -// if (!MerkleProof.verify(proof, merkleRoot, leaf)) { -// revert Callback_NotAuthorized(); -// } - -// // Return the allocated amount for the buyer -// return allocatedAmount; -// } - -// function _canBuy(address buyer_, uint256 amount_, uint256 allocatedAmount_) internal { -// // Check if the buyer has already spent their limit -// if (buyerSpent[buyer_] + amount_ > allocatedAmount_) { -// revert Callback_ExceedsLimit(); -// } - -// // Update the buyer spent amount -// buyerSpent[buyer_] += amount_; -// } - -// // ========== ADMIN FUNCTIONS ========== // - -// /// @notice Sets the merkle root for the allowlist -// /// This function can be called by the owner to update the merkle root after `onCreate()`. -// /// @dev This function performs the following: -// /// - Performs validation -// /// - Sets the merkle root -// /// - Emits a MerkleRootSet event -// /// -// /// This function reverts if: -// /// - The caller is not the owner -// /// - The auction has not been registered -// /// - The auction has been completed -// /// -// /// @param merkleRoot_ The new merkle root -// function setMerkleRoot( -// bytes32 merkleRoot_ -// ) external onlyOwner { -// // Revert if onCreate has not been called -// if (lotId == type(uint96).max) { -// revert Callback_InvalidState(); -// } - -// // Revert if the auction has been completed already -// if (auctionComplete) { -// revert Callback_InvalidState(); -// } - -// merkleRoot = merkleRoot_; - -// emit MerkleRootSet(merkleRoot_); -// } -// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol deleted file mode 100644 index bebe4e88..00000000 --- a/src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// import {MerkleProof} from "@openzeppelin-contracts-4.9.2/utils/cryptography/MerkleProof.sol"; - -// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; - -/// @notice Allowlist version of the Baseline Axis Launch callback. -/// @notice This version allows for a merkle tree to be used to determine which addresses are allowed to participate. However, the amount of quote tokens they can spend is not limited. -// contract BALwithAllowlist is BaselineAxisLaunch { -// // ========== ERRORS ========== // - -// /// @notice Error message when the callback state does not support the action -// error Callback_InvalidState(); - -// // ========== EVENTS ========== // - -// /// @notice Emitted when the merkle root is set -// event MerkleRootSet(bytes32 merkleRoot); - -// // ========== STATE VARIABLES ========== // - -// /// @notice The root of the merkle tree that represents the allowlist -// /// @dev The merkle tree should adhere to the format specified in the OpenZeppelin MerkleProof library at https://github.com/OpenZeppelin/merkle-tree -// /// In particular, leaf values (such as `(address)` or `(address,uint256)`) should be double-hashed. -// bytes32 public merkleRoot; - -// // ========== CONSTRUCTOR ========== // - -// // PERMISSIONS -// // onCreate: true -// // onCancel: true -// // onCurate: true -// // onPurchase: false -// // onBid: true -// // onSettle: true -// // receiveQuoteTokens: true -// // sendBaseTokens: true -// // Contract prefix should be: 11101111 = 0xEF - -// constructor( -// address auctionHouse_, -// address baselineKernel_, -// address reserve_, -// address owner_ -// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - -// // ========== CALLBACK FUNCTIONS ========== // - -// /// @inheritdoc BaselineAxisLaunch -// /// @dev This function reverts if: -// /// - `allowlistData_` is not of the correct length -// /// -// /// @param allowlistData_ abi-encoded data: (bytes32) representing the merkle root -// function __onCreate( -// uint96, -// address, -// address, -// address, -// uint256, -// bool, -// bytes memory allowlistData_ -// ) internal virtual override { -// // Check that the parameters are of the correct length -// if (allowlistData_.length != 32) { -// revert Callback_InvalidParams(); -// } - -// // Decode the merkle root from the callback data -// bytes32 merkleRootParams = abi.decode(allowlistData_, (bytes32)); - -// // Set the merkle root -// merkleRoot = merkleRootParams; -// emit MerkleRootSet(merkleRoot); -// } - -// /// @inheritdoc BaselineAxisLaunch -// /// -// /// @param callbackData_ abi-encoded data: (bytes32[]) representing the merkle proof -// function _onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual override { -// // Validate that the buyer is allowed to participate -// _canParticipate(buyer_, callbackData_); - -// // Call any additional implementation-specific logic -// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); -// } - -// /// @notice Override this function to implement additional functionality for the `onBid` callback -// /// -// /// @param lotId_ The ID of the lot -// /// @param bidId_ The ID of the bid -// /// @param buyer_ The address of the buyer -// /// @param amount_ The amount of quote tokens -// /// @param callbackData_ The callback data -// function __onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual {} - -// // ========== INTERNAL FUNCTIONS ========== // - -// function _canParticipate(address buyer_, bytes calldata callbackData_) internal view { -// // Decode the merkle proof from the callback data -// bytes32[] memory proof = abi.decode(callbackData_, (bytes32[])); - -// // Get the leaf for the buyer -// bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(buyer_)))); - -// // Validate the merkle proof -// if (!MerkleProof.verify(proof, merkleRoot, leaf)) { -// revert Callback_NotAuthorized(); -// } -// } - -// // ========== ADMIN FUNCTIONS ========== // - -// /// @notice Sets the merkle root for the allowlist -// /// This function can be called by the owner to update the merkle root after `onCreate()`. -// /// @dev This function performs the following: -// /// - Performs validation -// /// - Sets the merkle root -// /// - Emits a MerkleRootSet event -// /// -// /// This function reverts if: -// /// - The caller is not the owner -// /// - The auction has not been registered -// /// - The auction has been completed -// /// -// /// @param merkleRoot_ The new merkle root -// function setMerkleRoot( -// bytes32 merkleRoot_ -// ) external onlyOwner { -// // Revert if onCreate has not been called -// if (lotId == type(uint96).max) { -// revert Callback_InvalidState(); -// } - -// // Revert if the auction has been completed already -// if (auctionComplete) { -// revert Callback_InvalidState(); -// } - -// merkleRoot = merkleRoot_; - -// emit MerkleRootSet(merkleRoot_); -// } -// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol deleted file mode 100644 index 11fda2fa..00000000 --- a/src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; -// import {BALwithAllowlist} from "./BALwithAllowlist.sol"; - -/// @notice Capped allowlist version of the Baseline Axis Launch callback. -/// @notice This version allows for each address in the Merkle tree to have a standard amount of quote tokens they can spend. -// contract BALwithCappedAllowlist is BALwithAllowlist { -// // ========== ERRORS ========== // - -// /// @notice Error message when the bid amount exceeds the limit assigned to a buyer -// error Callback_ExceedsLimit(); - -// // ========== STATE VARIABLES ========== // - -// /// @notice The maximum amount a buyer can spend -// uint256 public buyerLimit; - -// /// @notice Tracks the cumulative amount spent by a buyer -// mapping(address => uint256) public buyerSpent; - -// // ========== CONSTRUCTOR ========== // - -// // PERMISSIONS -// // onCreate: true -// // onCancel: true -// // onCurate: true -// // onPurchase: false -// // onBid: true -// // onSettle: true -// // receiveQuoteTokens: true -// // sendBaseTokens: true -// // Contract prefix should be: 11101111 = 0xEF - -// constructor( -// address auctionHouse_, -// address baselineKernel_, -// address reserve_, -// address owner_ -// ) BALwithAllowlist(auctionHouse_, baselineKernel_, reserve_, owner_) {} - -// // ========== CALLBACK FUNCTIONS ========== // - -// /// @inheritdoc BaselineAxisLaunch -// /// @dev This function reverts if: -// /// - `allowlistData_` is not of the correct length -// /// -// /// @param allowlistData_ abi-encoded data: (bytes32, uint256) representing the merkle root and buyer limit -// function __onCreate( -// uint96, -// address, -// address, -// address, -// uint256, -// bool, -// bytes memory allowlistData_ -// ) internal override { -// // Check that the parameters are of the correct length -// if (allowlistData_.length != 64) { -// revert Callback_InvalidParams(); -// } - -// // Decode the merkle root from the callback data -// (bytes32 merkleRoot_, uint256 buyerLimit_) = abi.decode(allowlistData_, (bytes32, uint256)); - -// // Revert if buyer limit is 0, should just use regular allowlist version -// if (buyerLimit_ == 0) revert Callback_InvalidParams(); - -// // Set the merkle root and buyer limit -// merkleRoot = merkleRoot_; -// buyerLimit = buyerLimit_; -// emit MerkleRootSet(merkleRoot); -// } - -// /// @inheritdoc BALwithAllowlist -// /// @dev This function reverts if: -// /// - The buyer has already spent their limit -// function __onBid( -// uint96, -// uint64, -// address buyer_, -// uint256 amount_, -// bytes calldata -// ) internal override { -// // Validate that the buyer is allowed to participate -// _canBuy(buyer_, amount_); -// } - -// // ========== INTERNAL FUNCTIONS ========== // - -// function _canBuy(address buyer_, uint256 amount_) internal { -// // Check if the buyer has already spent their limit -// if (buyerSpent[buyer_] + amount_ > buyerLimit) { -// revert Callback_ExceedsLimit(); -// } - -// // Update the buyer spent amount -// buyerSpent[buyer_] += amount_; -// } -// } diff --git a/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol b/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol deleted file mode 100644 index e82b1245..00000000 --- a/src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol +++ /dev/null @@ -1,133 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.19; - -// import {BaselineAxisLaunch} from "./BaselineAxisLaunch.sol"; - -/// @notice Generic interface for tokens that implement a balanceOf function (includes ERC-20 and ERC-721) -interface ITokenBalance { - /// @notice Get the user's token balance - function balanceOf( - address user_ - ) external view returns (uint256); -} - -/// @notice TokenAllowlist version of the Baseline Axis Launch callback. -/// @notice Allowlist contract that checks if a user's balance of a token is above a threshold -/// @dev This shouldn't be used with liquid, transferable ERC-20s because it can easily be bypassed via flash loans or other swap mechanisms -/// @dev The intent is to use this with non-transferable tokens (e.g. vote escrow) or illiquid tokens that are not as easily manipulated, e.g. community NFTs -// contract BALwithTokenAllowlist is BaselineAxisLaunch { -// // ========== ERRORS ========== // - -// // ========== EVENTS ========== // - -// // ========== STATE VARIABLES ========== // - -// struct TokenCheck { -// ITokenBalance token; -// uint256 threshold; -// } - -// /// @notice Stores the token and balance threshold for the lot -// TokenCheck public tokenCheck; - -// // ========== CONSTRUCTOR ========== // - -// // PERMISSIONS -// // onCreate: true -// // onCancel: true -// // onCurate: true -// // onPurchase: false -// // onBid: true -// // onSettle: true -// // receiveQuoteTokens: true -// // sendBaseTokens: true -// // Contract prefix should be: 11101111 = 0xEF - -// constructor( -// address auctionHouse_, -// address baselineKernel_, -// address reserve_, -// address owner_ -// ) BaselineAxisLaunch(auctionHouse_, baselineKernel_, reserve_, owner_) {} - -// // ========== CALLBACK FUNCTIONS ========== // - -// /// @inheritdoc BaselineAxisLaunch -// /// @dev This function reverts if: -// /// - `allowlistData_` is not of the correct length -// /// -// /// @param allowlistData_ abi-encoded data: (ITokenBalance, uint96) representing the token contract and minimum balance -// function __onCreate( -// uint96, -// address, -// address, -// address, -// uint256, -// bool, -// bytes memory allowlistData_ -// ) internal virtual override { -// // Check that the parameters are of the correct length -// if (allowlistData_.length != 64) { -// revert Callback_InvalidParams(); -// } - -// // Decode the params to get the token contract and balance threshold -// (ITokenBalance token, uint96 threshold) = -// abi.decode(allowlistData_, (ITokenBalance, uint96)); - -// // Token must be a contract -// if (address(token).code.length == 0) revert Callback_InvalidParams(); - -// // Try to get balance for token, revert if it fails -// try token.balanceOf(address(this)) returns (uint256) {} -// catch { -// revert Callback_InvalidParams(); -// } - -// // Set the lot check -// tokenCheck = TokenCheck(token, threshold); -// } - -// /// @inheritdoc BaselineAxisLaunch -// /// -// /// @param callbackData_ abi-encoded data -// function _onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual override { -// // Validate that the buyer is allowed to participate -// _canParticipate(buyer_); - -// // Call any additional implementation-specific logic -// __onBid(lotId_, bidId_, buyer_, amount_, callbackData_); -// } - -// /// @notice Override this function to implement additional functionality for the `onBid` callback -// /// -// /// @param lotId_ The ID of the lot -// /// @param bidId_ The ID of the bid -// /// @param buyer_ The address of the buyer -// /// @param amount_ The amount of quote tokens -// /// @param callbackData_ The callback data -// function __onBid( -// uint96 lotId_, -// uint64 bidId_, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual {} - -// // ========== INTERNAL FUNCTIONS ========== // - -// function _canParticipate( -// address buyer_ -// ) internal view { -// // Check if the buyer's balance is above the threshold -// if (tokenCheck.token.balanceOf(buyer_) < tokenCheck.threshold) { -// revert Callback_NotAuthorized(); -// } -// } -// } diff --git a/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol b/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol deleted file mode 100644 index 043c19c4..00000000 --- a/src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol +++ /dev/null @@ -1,962 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-only -pragma solidity 0.8.19; - -// // Axis dependencies -// import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; -// import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -// import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; -// import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; -// import { -// Keycode as AxisKeycode, -// keycodeFromVeecode, -// fromKeycode as fromAxisKeycode -// } from "@axis-core-1.0.4/modules/Keycode.sol"; -// import {Module as AxisModule} from "@axis-core-1.0.4/modules/Modules.sol"; -// import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; -// import {Transfer} from "@axis-core-1.0.4/lib/Transfer.sol"; - -// // Baseline dependencies -// import { -// Kernel, -// Policy, -// Keycode as BaselineKeycode, -// toKeycode as toBaselineKeycode, -// Permissions as BaselinePermissions -// } from "./lib/Kernel.sol"; -// import {Position, Range, IBPOOLv1, IUniswapV3Pool} from "./lib/IBPOOL.sol"; -// import {ICREDTv1} from "./lib/ICREDT.sol"; -// import {ILOOPSv1} from "./lib/ILOOPS.sol"; - -// // Other libraries -// import {FixedPointMathLib} from "@solady-0.0.124/utils/FixedPointMathLib.sol"; -// import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; -// import {SqrtPriceMath} from "../../../lib/uniswap-v3/SqrtPriceMath.sol"; -// import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; - -/// @notice Axis auction callback to initialize a Baseline token using proceeds from a batch auction. -/// @dev This contract combines Baseline's InitializeProtocol Policy and Axis' Callback functionality to build an Axis auction callback specific to Baseline V2 token launches -/// It is designed to be used with a single auction and Baseline pool -// contract BaselineAxisLaunch is BaseCallback, Policy, Owned { -// using FixedPointMathLib for uint256; - -// // ========== ERRORS ========== // - -// /// @notice The address of the base token (passed in the `onCreate` callback) does not match the address of the bAsset that the callback was initialized with -// error Callback_Params_BAssetTokenMismatch(address baseToken_, address bAsset_); - -// /// @notice The address of the quote token (passed in the `onCreate` callback) does not match the address of the reserve that the callback was initialized with -// error Callback_Params_ReserveTokenMismatch(address quoteToken_, address reserve_); - -// /// @notice The auction format is not supported -// error Callback_Params_UnsupportedAuctionFormat(); - -// /// @notice The pool fee tier is not supported -// error Callback_Params_UnsupportedPoolFeeTier(); - -// /// @notice The anchor tick width is invalid -// error Callback_Params_InvalidAnchorTickWidth(); - -// /// @notice The discovery tick width is invalid -// error Callback_Params_InvalidDiscoveryTickWidth(); - -// /// @notice The floor range gap is invalid -// error Callback_Params_InvalidFloorRangeGap(); - -// /// @notice The anchor tick upper is invalid -// error Callback_Params_InvalidAnchorTickUpper(); - -// /// @notice The pool target tick is invalid -// /// @dev The pool target tick must be >= `anchorRangeLower` and <= `anchorRangeUpper` -// /// -// /// @param anchorRangeLower The lower tick of the anchor range -// /// @param anchorRangeUpper The upper tick of the anchor range -// error Callback_Params_InvalidPoolTargetTick(int24 anchorRangeLower, int24 anchorRangeUpper); - -// /// @notice One of the ranges is out of bounds -// error Callback_Params_RangeOutOfBounds(); - -// /// @notice The floor reserves percent is invalid -// error Callback_Params_InvalidFloorReservesPercent(); - -// /// @notice The pool percent is invalid -// error Callback_Params_InvalidPoolPercent(); - -// /// @notice The recipient address is invalid -// error Callback_Params_InvalidRecipient(); - -// /// @notice The auction tied to this callbacks contract has already been completed -// error Callback_AlreadyComplete(); - -// /// @notice The required funds were not sent to this callbacks contract -// error Callback_MissingFunds(); - -// /// @notice The initialization is invalid -// error Callback_InvalidInitialization(); - -// /// @notice The capacity ratio is invalid -// /// -// /// @param capacityRatio The ratio of the pool capacity to the circulating supply -// error Callback_InvalidCapacityRatio(uint256 capacityRatio); - -// /// @notice The pool price is lower than the auction price -// /// -// /// @param currentTick The current tick of the pool -// /// @param auctionTick The tick corresponding to the auction price -// error Callback_PoolLessThanAuctionPrice(int24 currentTick, int24 auctionTick); - -// /// @notice The BPOOL reserve token does not match the configured `RESERVE` address -// error Callback_BPOOLReserveMismatch(); - -// /// @notice The address of the BPOOL is higher than the RESERVE token address, when it must be lower -// error Callback_BPOOLInvalidAddress(); - -// /// @notice The caller to the Uniswap V3 swap callback is invalid -// error Callback_Swap_InvalidCaller(); - -// /// @notice The case for the Uniswap V3 swap callback is invalid -// error Callback_Swap_InvalidCase(); - -// // ========== EVENTS ========== // - -// event LiquidityDeployed( -// int24 floorTickLower, int24 anchorTickUpper, uint128 floorLiquidity, uint128 anchorLiquidity -// ); - -// // ========== DATA STRUCTURES ========== // - -// /// @notice Data struct for the onCreate callback -// /// -// /// @param recipient The address to receive proceeds that do not go to the pool -// /// @param poolPercent The percentage of the proceeds to allocate to the pool, in basis points (1% = 100). The remainder will be sent to the `recipient`. -// /// @param floorReservesPercent The percentage of the pool proceeds to allocate to the floor range, in basis points (1% = 100). The remainder will be allocated to the anchor range. -// /// @param floorRangeGap The gap between the floor and anchor ranges, as a multiple of the pool tick spacing. -// /// @param anchorTickU The upper tick of the anchor range. Validated against the calculated upper bound of the anchor range. This is provided off-chain to prevent front-running. -// /// @param anchorTickWidth The width of the anchor tick range, as a multiple of the pool tick spacing. -// /// @param poolTargetTick The target tick for the pool. This is provided off-chain to prevent front-running. -// /// @param allowlistParams Additional parameters for an allowlist, passed to `__onCreate()` for further processing -// struct CreateData { -// address recipient; -// uint24 poolPercent; -// uint24 floorReservesPercent; -// int24 floorRangeGap; -// int24 anchorTickU; -// int24 anchorTickWidth; -// int24 poolTargetTick; -// bytes allowlistParams; -// } - -// // ========== CONSTANTS ========== // - -// /// @notice The minimum tick value -// int24 internal constant _MIN_TICK = -887_272; - -// /// @notice The maximum tick value -// int24 internal constant _MAX_TICK = 887_272; - -// /// @notice The value for 100% -// // solhint-disable-next-line private-vars-leading-underscore -// uint48 internal constant ONE_HUNDRED_PERCENT = 100e2; - -// /// @notice The tick spacing width of the discovery range -// int24 internal constant _DISCOVERY_TICK_SPACING_WIDTH = 350; - -// // ========== STATE VARIABLES ========== // - -// // Baseline Modules -// // solhint-disable var-name-mixedcase -// IBPOOLv1 public BPOOL; -// ICREDTv1 public CREDT; -// ILOOPSv1 public LOOPS; - -// // Pool variables -// ERC20 public immutable RESERVE; -// // solhint-enable var-name-mixedcase -// ERC20 public bAsset; - -// // Axis Auction Variables - -// /// @notice Lot ID of the auction for the baseline market. This callback only supports one lot. -// /// @dev This value is initialised with the uint96 max value to indicate that it has not been set yet. -// uint96 public lotId; - -// /// @notice Indicates whether the auction is complete -// /// @dev This is used to prevent the callback from being called multiple times. It is set in the `onSettle()` callback. -// bool public auctionComplete; - -// /// @notice The percentage of the proceeds to allocate to the pool -// /// @dev This value is set in the `onCreate()` callback. -// uint24 public poolPercent; - -// /// @notice The percentage of the proceeds to allocate to the floor range -// /// @dev This value is set in the `onCreate()` callback. -// uint24 public floorReservesPercent; - -// /// @notice The address to receive proceeds that do not go to the pool -// /// @dev This value is set in the `onCreate()` callback. -// address public recipient; - -// /// @notice The target tick for the pool -// /// @dev This value is set in the `onCreate()` callback. -// int24 public poolTargetTick; - -// // ========== CONSTRUCTOR ========== // - -// /// @notice Constructor for BaselineAxisLaunch -// /// -// /// @param auctionHouse_ The AuctionHouse the callback is paired with -// /// @param baselineKernel_ Address of the Baseline kernel -// /// @param reserve_ Address of the reserve token. This should match the quote token for the auction lot. -// /// @param owner_ Address of the owner of the contract. Must be the same as the eventual seller of the auction lot. -// constructor( -// address auctionHouse_, -// address baselineKernel_, -// address reserve_, -// address owner_ -// ) -// BaseCallback( -// auctionHouse_, -// Callbacks.Permissions({ -// onCreate: true, -// onCancel: true, -// onCurate: true, -// onPurchase: false, -// onBid: true, -// onSettle: true, -// receiveQuoteTokens: true, -// sendBaseTokens: true -// }) -// ) -// Policy(Kernel(baselineKernel_)) -// Owned(owner_) -// { -// // Set lot ID to max uint(96) initially so it doesn't reference a lot -// lotId = type(uint96).max; - -// // Set the reserve token -// RESERVE = ERC20(reserve_); -// } - -// // ========== POLICY FUNCTIONS ========== // - -// /// @inheritdoc Policy -// function configureDependencies() -// external -// override -// onlyKernel -// returns (BaselineKeycode[] memory dependencies) -// { -// BaselineKeycode bpool = toBaselineKeycode("BPOOL"); -// BaselineKeycode credt = toBaselineKeycode("CREDT"); -// BaselineKeycode loops = toBaselineKeycode("LOOPS"); - -// // Populate the dependencies array -// dependencies = new BaselineKeycode[](3); -// dependencies[0] = bpool; -// dependencies[1] = credt; -// dependencies[2] = loops; - -// // Set local values -// BPOOL = IBPOOLv1(getModuleAddress(bpool)); -// bAsset = ERC20(address(BPOOL)); -// CREDT = ICREDTv1(getModuleAddress(credt)); -// LOOPS = ILOOPSv1(getModuleAddress(loops)); - -// // Require that the BPOOL's reserve token be the same as the callback's reserve token -// if (address(BPOOL.reserve()) != address(RESERVE)) revert Callback_BPOOLReserveMismatch(); -// } - -// /// @inheritdoc Policy -// function requestPermissions() -// external -// view -// override -// onlyKernel -// returns (BaselinePermissions[] memory requests) -// { -// BaselineKeycode bpool = toBaselineKeycode("BPOOL"); - -// requests = new BaselinePermissions[](6); -// requests[0] = BaselinePermissions(bpool, BPOOL.addReservesTo.selector); -// requests[1] = BaselinePermissions(bpool, BPOOL.addLiquidityTo.selector); -// requests[2] = BaselinePermissions(bpool, BPOOL.burnAllBAssetsInContract.selector); -// requests[3] = BaselinePermissions(bpool, BPOOL.mint.selector); -// requests[4] = BaselinePermissions(bpool, BPOOL.setTicks.selector); -// requests[5] = BaselinePermissions(bpool, BPOOL.setTransferLock.selector); -// } - -// // ========== MODIFIERS ========== // - -// /// @notice Validates that the lot id matches the stored lot id -// modifier onlyValidLot( -// uint96 lotId_ -// ) { -// if (lotId_ != lotId) revert Callback_InvalidParams(); -// _; -// } - -// /// @notice Validates that the auction is not already settled or cancelled -// modifier onlyActiveLot() { -// if (auctionComplete) revert Callback_AlreadyComplete(); -// _; -// } - -// // ========== CALLBACK FUNCTIONS ========== // - -// // CALLBACK PERMISSIONS -// // onCreate: true -// // onCancel: true -// // onCurate: true -// // onPurchase: false -// // onBid: true -// // onSettle: true -// // receiveQuoteTokens: true -// // sendBaseTokens: true -// // Contract prefix should be: 11101111 = 0xEF - -// /// @inheritdoc BaseCallback -// /// @dev This function performs the following: -// /// - Performs validation -// /// - Sets the `lotId`, `percentReservesFloor`, `anchorTickWidth`, and `discoveryTickWidth` variables -// /// - Calls the allowlist callback -// /// - Performs a solvency check to ensure the pool can support the intended supply -// /// - Mints the required bAsset tokens to the AuctionHouse -// /// -// /// This function has the following assumptions: -// /// - Any Baseline credit allocations have been minted and allocated prior to auction creation (and this callback) -// /// -// /// This function reverts if: -// /// - `seller_` is not the owner -// /// - `baseToken_` is not the same as `bAsset` -// /// - `quoteToken_` is not the same as `RESERVE` -// /// - `baseToken_` is not lower than `quoteToken_` -// /// - `recipient` is the zero address -// /// - `lotId` is already set -// /// - The pool fee tier is not supported -// /// - The auction format is not supported -// /// - The auction is not prefunded -// /// - `CreateData.floorReservesPercent` is less than 10% or greater than 99% -// /// - `CreateData.poolPercent` is less than 10% or greater than 100% -// /// - `CreateData.floorRangeGap` is < 0 -// /// - `CreateData.anchorTickWidth` is < 10 or > 50 -// /// - `CreateData.anchorTickU` is not the same as the calculated value -// /// - `CreateData.poolTargetTick` is not >= anchorRangeLower and < anchorRangeUpper -// /// - Any of the tick ranges would exceed the tick bounds -// /// - The pool tick is less than the auction price (in terms of ticks) -// /// - The pool capacity is not sufficient to support the intended supply -// function _onCreate( -// uint96 lotId_, -// address seller_, -// address baseToken_, -// address quoteToken_, -// uint256 capacity_, -// bool prefund_, -// bytes calldata callbackData_ -// ) internal override { -// // Validate that the seller is the owner -// // Otherwise this single-use callback could be used by anyone -// if (seller_ != owner) { -// revert Callback_NotAuthorized(); -// } - -// // Validate the base token is the baseline token -// // and the quote token is the reserve -// if (baseToken_ != address(bAsset)) { -// revert Callback_Params_BAssetTokenMismatch(baseToken_, address(bAsset)); -// } -// if (quoteToken_ != address(RESERVE)) { -// revert Callback_Params_ReserveTokenMismatch(quoteToken_, address(RESERVE)); -// } -// // Ensure the base token is lower than the quote token -// if (address(bAsset) > address(RESERVE)) { -// revert Callback_BPOOLInvalidAddress(); -// } - -// // Validate that the lot ID is not already set -// if (lotId != type(uint96).max) revert Callback_InvalidParams(); - -// // Decode the provided callback data (must be correctly formatted even if not using parts of it) -// CreateData memory cbData = abi.decode(callbackData_, (CreateData)); - -// // Validate that the recipient is not the zero address -// if (cbData.recipient == address(0)) revert Callback_Params_InvalidRecipient(); - -// // Validate that the pool fee tier is supported -// // This callback only supports the 1% fee tier (tick spacing = 200) -// // as other fee tiers are not supported by the Baseline pool -// if (BPOOL.TICK_SPACING() != 200) revert Callback_Params_UnsupportedPoolFeeTier(); - -// // Validate that the floor range gap is at least 0 -// if (cbData.floorRangeGap < 0) revert Callback_Params_InvalidFloorRangeGap(); - -// // Validate that the anchor tick width is at least 10 tick spacing and at most 50 -// // Baseline supports only within this range -// if (cbData.anchorTickWidth < 10 || cbData.anchorTickWidth > 50) { -// revert Callback_Params_InvalidAnchorTickWidth(); -// } - -// // Validate that the floor reserves percent is between 10% and 90% -// // If the floor reserves are too low, it can render `MarketMaking.slide()` inoperable -// // If the floor reserves are too high, it can render `MarketMaking.sweep()` inoperable -// // as the anchor and discovery liquidity will be too thin -// if (cbData.floorReservesPercent < 10e2 || cbData.floorReservesPercent > 99e2) { -// revert Callback_Params_InvalidFloorReservesPercent(); -// } - -// // Validate that the pool percent is at least 10% and at most 100% -// if (cbData.poolPercent < 10e2 || cbData.poolPercent > 100e2) { -// revert Callback_Params_InvalidPoolPercent(); -// } - -// // Auction must be prefunded for batch auctions (which is the only type supported with this callback), -// // this can't fail because it's checked in the AH as well, but including for completeness -// if (!prefund_) revert Callback_Params_UnsupportedAuctionFormat(); - -// // Set the lot ID -// lotId = lotId_; - -// // Set the recipient -// recipient = cbData.recipient; - -// // Set the pool percent -// poolPercent = cbData.poolPercent; - -// // Set the floor reserves percent -// floorReservesPercent = cbData.floorReservesPercent; - -// // Only supports Fixed Price Batch Auctions initially -// { -// // Get the auction format -// AxisKeycode auctionFormat = keycodeFromVeecode( -// AxisModule(address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_))) -// .VEECODE() -// ); - -// if (fromAxisKeycode(auctionFormat) != bytes5("FPBA")) { -// revert Callback_Params_UnsupportedAuctionFormat(); -// } -// } - -// // This contract can be extended with an allowlist for the auction -// // Call a lower-level function where this information can be used -// // We do this before token interactions to conform to CEI -// __onCreate( -// lotId_, seller_, baseToken_, quoteToken_, capacity_, prefund_, cbData.allowlistParams -// ); - -// // Set the ticks for the Baseline pool initially with the following assumptions: -// // - The floor range is 1 tick spacing wide -// // - The anchor range is `anchorTickWidth` tick spacings wide, above the floor range -// // - The discovery range is `discoveryTickWidth` tick spacings wide, above the anchor range -// // - The anchor range contains the active tick -// // - The anchor range upper tick is the active tick rounded up to the nearest tick spacing -// // - The other range boundaries are calculated accordingly -// { -// // Check that the anchor tick range upper bound is the same -// // as the closest tick spacing boundary above the active tick on the BPOOL -// // We check this value against a parameter instead of reading -// // directly to avoid a situation where someone front-runs the -// // auction creation transaction and moves the active tick -// if (cbData.anchorTickU != BPOOL.getActiveTS()) { -// revert Callback_Params_InvalidAnchorTickUpper(); -// } -// int24 anchorRangeUpper = cbData.anchorTickU; - -// // Get the tick spacing from the pool -// int24 tickSpacing = BPOOL.TICK_SPACING(); - -// // Anchor range lower is the anchor tick width below the anchor range upper -// int24 anchorRangeLower = anchorRangeUpper - cbData.anchorTickWidth * tickSpacing; - -// // Validate that the pool target tick is within the anchor range -// // The `_onSettle()` function will perform swaps (if necessary) to move the pool tick to the target tick in order to mitigate manipulation. -// // The value must be in the anchor range and below the anchor upper tick (which is where the discovery range begins). -// if ( -// cbData.poolTargetTick < anchorRangeLower -// || cbData.poolTargetTick >= anchorRangeUpper -// ) { -// revert Callback_Params_InvalidPoolTargetTick(anchorRangeLower, anchorRangeUpper); -// } -// poolTargetTick = cbData.poolTargetTick; - -// // Set the anchor range -// BPOOL.setTicks(Range.ANCHOR, anchorRangeLower, anchorRangeUpper); - -// // Set the floor range -// // The creator can provide the `floorRangeGap` to space the floor range from the anchor range -// // If `floorRangeGap` is 0, the floor range will be directly below the anchor range -// // The floor range is one tick spacing wide -// int24 floorRangeUpper = anchorRangeLower - cbData.floorRangeGap * tickSpacing; -// int24 floorRangeLower = floorRangeUpper - tickSpacing; - -// BPOOL.setTicks(Range.FLOOR, floorRangeLower, floorRangeUpper); - -// // Set the discovery range -// int24 discoveryRangeUpper = -// anchorRangeUpper + tickSpacing * _DISCOVERY_TICK_SPACING_WIDTH; -// BPOOL.setTicks(Range.DISCOVERY, anchorRangeUpper, discoveryRangeUpper); - -// // If the floor range lower tick (or any other above it) is below the min tick, it will cause problems -// // If the discovery range upper tick (or any other below it) is above the max tick, it will cause problems -// if (floorRangeLower < _MIN_TICK || discoveryRangeUpper > _MAX_TICK) { -// revert Callback_Params_RangeOutOfBounds(); -// } -// } - -// // Perform a pre-check to make sure the setup can be valid -// // This avoids certain bad configurations that would lead to failed initializations -// // Specifically, we check that the pool can support the intended supply -// // factoring in the capacity, curator fee, and any additional spot or collateralized supply -// // that already exists. -// // We assume that the auction capacity will be completely filled. This can be guaranteed by -// // setting the minFillPercent to 100e2 on the auction. -// { -// // Calculate the initial circulating supply (including collateralized supply) -// uint256 initialCircSupply; -// { -// // Get the current supply values -// uint256 totalSupply = bAsset.totalSupply(); // can use totalSupply here since no bAssets are in the pool yet - -// // Calculate the maximum curator fee that can be paid -// (,, uint48 curatorFeePerc,,) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); -// uint256 curatorFee = (capacity_ * curatorFeePerc) / ONE_HUNDRED_PERCENT; - -// // Capacity and curator fee have not yet been minted, so we add those -// // Collateralized supply is already minted and included in total supply, so we do not need to add it -// initialCircSupply = totalSupply + capacity_ + curatorFee; -// } - -// // Calculate the initial capacity of the pool based on the ticks set and the expected proceeds to deposit in the pool -// uint256 initialCapacity; -// { -// // Get the fixed price from the auction module -// // This value is in the number of reserve tokens per baseline token -// uint256 auctionPrice; -// { -// auctionPrice = IFixedPriceBatch( -// address(IAuctionHouse(AUCTION_HOUSE).getAuctionModuleForId(lotId_)) -// ).getAuctionData(lotId_).price; -// } - -// // Get the active tick from the pool and confirm it is >= the auction price corresponds to -// { -// // We do this to avoid a situation where buyers are disincentivized to bid on the auction -// // Pool price is number of token1 (reserve) per token0 (bAsset), which is what we want, but it needs to be squared -// (, int24 activeTick,,,,,) = BPOOL.pool().slot0(); - -// // Calculate the tick for the auction price -// // `getSqrtPriceX96` handles token ordering -// // The resulting tick will incorporate any differences in decimals between the tokens -// uint160 sqrtPriceX96 = SqrtPriceMath.getSqrtPriceX96( -// address(RESERVE), address(bAsset), auctionPrice, 10 ** bAsset.decimals() -// ); -// int24 auctionTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); - -// // Verify that the active tick is at least the auction tick -// if (activeTick < auctionTick) { -// revert Callback_PoolLessThanAuctionPrice(activeTick, auctionTick); -// } -// } - -// uint256 poolProceeds = ( -// _getExpectedProceeds(lotId_, capacity_, auctionPrice) * poolPercent -// ) / ONE_HUNDRED_PERCENT; - -// // Calculate the expected reserves for the floor and anchor ranges -// uint256 floorReserves = (poolProceeds * floorReservesPercent) / ONE_HUNDRED_PERCENT; -// uint256 anchorReserves = poolProceeds - floorReserves; - -// // Calculate the expected capacity of the pool -// // Skip discovery range since no reserves will be deposited in it -// Position memory floor = BPOOL.getPosition(Range.FLOOR); -// Position memory anchor = BPOOL.getPosition(Range.ANCHOR); - -// uint256 floorCapacity = -// BPOOL.getCapacityForReserves(floor.sqrtPriceL, floor.sqrtPriceU, floorReserves); -// uint256 anchorCapacity = BPOOL.getCapacityForReserves( -// anchor.sqrtPriceL, anchor.sqrtPriceU, anchorReserves -// ); - -// // Calculate the debt capacity at the floor range -// uint256 debtCapacity = BPOOL.getCapacityForReserves( -// floor.sqrtPriceL, -// floor.sqrtPriceU, -// CREDT.totalCreditIssued() + LOOPS.totalDebt() -// ); - -// // Calculate the total initial capacity of the pool -// initialCapacity = debtCapacity + floorCapacity + anchorCapacity; -// } - -// // Verify the liquidity can support the intended supply -// // and that there is no significant initial surplus -// // -// // If the solvency check is failing, it can be resolved by adjusting the following: -// // - auction price (via the auction fixed price) -// // - system liquidity (via the pool allocation and floor reserves allocation) -// uint256 capacityRatio = initialCapacity.divWad(initialCircSupply); -// if (capacityRatio < 100e16 || capacityRatio > 102e16) { -// revert Callback_InvalidCapacityRatio(capacityRatio); -// } -// } - -// // Unlock BPOOL transfers -// BPOOL.setTransferLock(false); - -// // Mint the capacity of baseline tokens to the auction house to prefund the auction -// BPOOL.mint(msg.sender, capacity_); - -// // Lock BPOOL transfers -// // This is to prevent any transfers of bAssets until the auction is settled -// // The BPOOL will need to be manually unlocked prior to the auction being cancelled or settled -// BPOOL.setTransferLock(true); -// } - -// /// @notice Override this function to implement allowlist functionality -// function __onCreate( -// uint96 lotId_, -// address seller_, -// address baseToken_, -// address quoteToken_, -// uint256 capacity_, -// bool prefund_, -// bytes memory allowlistData_ -// ) internal virtual {} - -// /// @inheritdoc BaseCallback -// /// @dev This function performs the following: -// /// - Performs validation -// /// - Burns the refunded bAsset tokens -// /// -// /// This function has the following assumptions: -// /// - BaseCallback has already validated the lot ID -// /// - The AuctionHouse has already sent the correct amount of bAsset tokens -// /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of BPOOL tokens from the AuctionHouse to the callback -// /// -// /// This function reverts if: -// /// - `lotId_` is not the same as the stored `lotId` -// /// - The auction is already complete -// /// - Sufficient quantity of `bAsset` have not been sent to the callback -// function _onCancel( -// uint96 lotId_, -// uint256 refund_, -// bool, -// bytes calldata -// ) internal override onlyValidLot(lotId_) onlyActiveLot { -// // Burn any refunded tokens (all auctions are prefunded) -// // Verify that the callback received the correct amount of bAsset tokens -// if (bAsset.balanceOf(address(this)) < refund_) revert Callback_MissingFunds(); - -// // Set the auction lot to be cancelled -// auctionComplete = true; - -// // Unlock BPOOL transfers -// BPOOL.setTransferLock(false); - -// // Send tokens to BPOOL and then burn -// Transfer.transfer(bAsset, address(BPOOL), refund_, false); -// BPOOL.burnAllBAssetsInContract(); - -// // Lock BPOOL transfers -// BPOOL.setTransferLock(true); -// } - -// /// @inheritdoc BaseCallback -// /// @dev This function performs the following: -// /// - Performs validation -// /// -// /// This function has the following assumptions: -// /// - BaseCallback has already validated the lot ID -// /// -// /// This function reverts if: -// /// - `lotId_` is not the same as the stored `lotId` -// /// - The curator fee is non-zero -// function _onCurate( -// uint96 lotId_, -// uint256 curatorFee_, -// bool, -// bytes calldata -// ) internal override onlyValidLot(lotId_) onlyActiveLot { -// // Mint tokens for curator fee if it's not zero -// if (curatorFee_ > 0) { -// // Unlock BPOOL transfers -// BPOOL.setTransferLock(false); - -// BPOOL.mint(msg.sender, curatorFee_); - -// // Lock BPOOL transfers -// BPOOL.setTransferLock(true); -// } -// } - -// /// @inheritdoc BaseCallback -// /// @dev Not implemented since atomic auctions are not supported -// function _onPurchase( -// uint96, -// address, -// uint256, -// uint256, -// bool, -// bytes calldata -// ) internal pure override { -// revert Callback_NotImplemented(); -// } - -// /// @inheritdoc BaseCallback -// /// @dev No logic is needed for this function here, but it can be overridden by a lower-level contract to provide allowlist functionality -// function _onBid( -// uint96 lotId_, -// uint64 bidId, -// address buyer_, -// uint256 amount_, -// bytes calldata callbackData_ -// ) internal virtual override {} - -// /// @inheritdoc BaseCallback -// /// @dev This function performs the following: -// /// - Performs validation -// /// - Sets the auction as complete -// /// - Burns any refunded bAsset tokens -// /// - Ensures that the pool is at the correct price -// /// - Deploys reserves and liquidity into the Baseline pool -// /// - Performs a solvency check to ensure the pool can support the supply -// /// - Transfers any remaining proceeds (reserves) to the recipient -// /// -// /// Next steps: -// /// - Activate the market making and credit facility policies in the Baseline stack, which cannot be enabled before the auction is settled and the pool is initialized -// /// -// /// This function has the following assumptions: -// /// - BaseCallback has already validated the lot ID -// /// - The AuctionHouse has already sent the correct amount of quote tokens (proceeds) -// /// - The AuctionHouse has already sent the correct amount of refunded base tokens -// /// - The AuctionHouse is pre-funded, so does not require additional base tokens (bAssets) to be supplied -// /// - No new Baseline credit allocations have been made since the auction was created (and `onCreate` was called) -// /// - The auction seller has manually unlocked BPOOL transfers, in order to allow the transfer of refunded BPOOL tokens from the AuctionHouse to the callback -// /// -// /// This function reverts if: -// /// - `lotId_` is not the same as the stored `lotId` -// /// - The auction is already complete -// /// - The reported proceeds received are less than the reserve balance -// /// - The reported refund received is less than the bAsset balance -// /// - The pool price is not at the target price -// /// - The pool capacity is not sufficient to support the intended supply -// /// -// /// Note that while the solvency check in both `onCreate` and `onSettle` are consistent, if the auction is not fully subscribed (and hence there is a refund), it can cause the solvency check to fail in `onSettle`. -// function _onSettle( -// uint96 lotId_, -// uint256 proceeds_, -// uint256 refund_, -// bytes calldata -// ) internal virtual override onlyValidLot(lotId_) onlyActiveLot { -// // Validate that the callback received the correct amount of proceeds -// // As this is a single-use contract, reserve balance is likely 0 prior, but extra funds will not affect it -// if (proceeds_ > RESERVE.balanceOf(address(this))) revert Callback_MissingFunds(); - -// // Validate that the callback received the correct amount of base tokens as a refund -// // As this is a single-use contract and we control the minting of bAssets, bAsset balance is 0 prior -// if (refund_ > bAsset.balanceOf(address(this))) revert Callback_MissingFunds(); - -// // Set the auction as complete -// auctionComplete = true; - -// //// Step 1: Burn any refunded bAsset tokens //// -// // Unlock BPOOL transfers -// BPOOL.setTransferLock(false); - -// // Burn any refunded bAsset tokens that were sent from the auction house -// Transfer.transfer(bAsset, address(BPOOL), refund_, false); -// BPOOL.burnAllBAssetsInContract(); - -// //// Step 2: Ensure the pool is at the correct price //// -// // Since there is no bAsset liquidity deployed yet, -// // External LPs can move the current price of the pool. -// // We move it back to the target active tick to ensure -// // the pool is at the correct price. -// { -// IUniswapV3Pool pool = BPOOL.pool(); - -// // Current price of the pool -// (uint160 currentSqrtPrice,,,,,,) = pool.slot0(); - -// // Get the target sqrt price from the target tick -// uint160 targetSqrtPrice = TickMath.getSqrtRatioAtTick(poolTargetTick); - -// // We assume there are no circulating bAssets that could be provided as liquidity yet. -// // Therefore, there are three cases: -// // 1. The current price is above the target price -// if (currentSqrtPrice > targetSqrtPrice) { -// // In this case, an external LP has provided reserve liquidity above our range. -// // We can sell bAssets into this liquidity and the external LP will effectively be -// // bAssets at a premium to the initial price of the pool. -// // This does not affect the solvency of the system since the reserves received -// // are greater than the tokens minted, but it may cause the system to be -// // initialized with a surplus, which would allow for an immediate bump or snipe. -// // -// // We want to swap out all of the reserves currently in the pool above the target price for bAssets. -// // We just use the total balance in the pool because the price limit will prevent buying lower. -// int256 amount1Out = -int256(RESERVE.balanceOf(address(pool))); - -// // If there is no liquidity in the pool, this ensures that the swap will suceed -// if (amount1Out == 0) amount1Out = -1; - -// pool.swap( -// address(this), // recipient -// true, // zeroToOne, swapping token0 (bAsset) for token1 (reserve) so this is true -// amount1Out, // amountSpecified, positive is exactIn, negative is exactOut -// targetSqrtPrice, // sqrtPriceLimitX96 -// abi.encode(1) // data, case 1 -// ); -// } -// // 2. The current price is below the target price -// else if (currentSqrtPrice < targetSqrtPrice) { -// // Swap 1 wei of token1 (reserve) for token0 (bAsset) with a limit at the targetSqrtPrice -// // There are no bAssets in the pool, so we receive none. Because of this, -// // we don't end up paying any reserves either, but the price of the pool is shifted. -// pool.swap( -// address(this), // recipient -// false, // zeroToOne, swapping token1 (reserve) for token0 (bAsset) so this is false -// int256(1), // amountSpecified, positive is exactIn, negative is exactOut -// targetSqrtPrice, // sqrtPriceLimitX96 -// abi.encode(2) // data, case 2 -// ); -// } -// // 3. The current price is at the target price. -// // If so, we don't need to do anything. - -// // We don't need to track any of these amounts because the liquidity deployment and -// // will handle any extra reserves and the solvency check ensures that the system -// // can support the supply. - -// // Check that the price is now at the target price -// (currentSqrtPrice,,,,,,) = pool.slot0(); -// if (currentSqrtPrice != targetSqrtPrice) { -// revert Callback_InvalidInitialization(); -// } -// } - -// //// Step 3: Deploy liquidity to the Baseline pool //// - -// // Calculate reserves to add to the pool -// // Because we potentially extracted reserves from the pool in the previous step, -// // we use the current balance minus the seller proceeds from the auction as -// // the pool proceeds amount so that the surplus is provided to the pool. -// // If no reserves were extracted, this will be the same amount as expected. -// uint256 sellerProceeds = -// proceeds_ * (ONE_HUNDRED_PERCENT - poolPercent) / ONE_HUNDRED_PERCENT; - -// uint256 poolProceeds = RESERVE.balanceOf(address(this)) - sellerProceeds; - -// // Approve spending of the reserve token -// Transfer.approve(RESERVE, address(BPOOL), poolProceeds); - -// // Add the configured percentage of the proceeds to the Floor range -// uint256 floorReserves = poolProceeds * floorReservesPercent / ONE_HUNDRED_PERCENT; -// BPOOL.addReservesTo(Range.FLOOR, floorReserves); - -// // Add the remainder of the proceeds to the Anchor range -// BPOOL.addReservesTo(Range.ANCHOR, poolProceeds - floorReserves); - -// // Ensure that there are no dangling approvals -// Transfer.approve(RESERVE, address(BPOOL), 0); - -// // Add proportional liquidity to the Discovery range. -// // Only the anchor range is used, otherwise the liquidity would be too thick. -// // The anchor range is guranteed to have a tick spacing width -// // and to have reserves of at least 1% of the proceeds. -// BPOOL.addLiquidityTo(Range.DISCOVERY, BPOOL.getLiquidity(Range.ANCHOR) * 11 / 10); - -// //// Step 4: Send remaining proceeds (and any excess reserves) to the recipient //// -// Transfer.transfer(RESERVE, recipient, RESERVE.balanceOf(address(this)), false); - -// //// Step 5: Verify Solvency //// -// { -// Position memory floor = BPOOL.getPosition(Range.FLOOR); -// Position memory anchor = BPOOL.getPosition(Range.ANCHOR); -// Position memory discovery = BPOOL.getPosition(Range.DISCOVERY); - -// // Calculate the debt capacity at the floor range -// uint256 debtCapacity = BPOOL.getCapacityForReserves( -// floor.sqrtPriceL, floor.sqrtPriceU, CREDT.totalCreditIssued() + LOOPS.totalDebt() -// ); - -// uint256 totalCapacity = -// debtCapacity + floor.capacity + anchor.capacity + discovery.capacity; -// // Includes collateralised supply -// uint256 totalSpotSupply = -// bAsset.totalSupply() - floor.bAssets - anchor.bAssets - discovery.bAssets; - -// // verify the liquidity can support the intended supply -// // we do not check for a surplus at this point to avoid a DoS attack vector -// // during the onCreate callback, we check for a surplus and there shouldn't -// // be one from this initialization at this point. -// // any surplus reserves added to the pool by a 3rd party before -// // the system is initialized will be snipable and effectively donated to the snipers -// uint256 capacityRatio = totalCapacity.divWad(totalSpotSupply); -// if (capacityRatio < 100e16) { -// revert Callback_InvalidCapacityRatio(capacityRatio); -// } -// } - -// // Lock BPOOL transfers to prevent any token interactions until the system is ready -// BPOOL.setTransferLock(true); - -// // Emit an event -// { -// (int24 floorTickLower,) = BPOOL.getTicks(Range.FLOOR); -// (, int24 anchorTickUpper) = BPOOL.getTicks(Range.ANCHOR); -// emit LiquidityDeployed( -// floorTickLower, -// anchorTickUpper, -// BPOOL.getLiquidity(Range.FLOOR), -// BPOOL.getLiquidity(Range.ANCHOR) -// ); -// } -// } - -// // ========== INTERNAL FUNCTIONS ========== // - -// /// @notice Calculate the expected proceeds from the auction and how much will be deposited in the pool -// /// @dev The proceeds sent to the onSettle callback function will exclude any protocol and referrer fees, so this calculation mimics the behaviour -// /// -// /// @param lotId_ Lot ID of the auction -// /// @param auctionPrice_ Price of the auction -// /// @param capacity_ Capacity of the auction -// /// @return proceeds Expected proceeds from the auction -// function _getExpectedProceeds( -// uint96 lotId_, -// uint256 auctionPrice_, -// uint256 capacity_ -// ) internal view returns (uint256) { -// // Get the fees from the auction house -// (,,, uint48 protocolFee, uint48 referrerFee) = IAuctionHouse(AUCTION_HOUSE).lotFees(lotId_); - -// // Calculate the expected proceeds after fees -// uint256 proceedsBeforeFees = (auctionPrice_ * capacity_) / (10 ** bAsset.decimals()); -// return proceedsBeforeFees - (proceedsBeforeFees * protocolFee) / ONE_HUNDRED_PERCENT -// - (proceedsBeforeFees * referrerFee) / ONE_HUNDRED_PERCENT; -// } - -// // ========== UNIV3 FUNCTIONS ========== // - -// // Provide tokens when adjusting the pool price via a swap before deploying liquidity -// function uniswapV3SwapCallback(int256 bAssetDelta_, int256, bytes calldata data_) external { -// // Only the pool can call -// address pool = address(BPOOL.pool()); -// if (msg.sender != pool) revert Callback_Swap_InvalidCaller(); - -// // Decode the data -// (uint8 case_) = abi.decode(data_, (uint8)); - -// // Handle the swap case -// if (case_ == 1) { -// // Mint the bAsset delta to the pool (if greater than 0) -// if (bAssetDelta_ > 0) { -// BPOOL.mint(pool, uint256(bAssetDelta_)); -// } -// } else if (case_ == 2) { -// // Case 2: Swapped in 1 wei of reserve tokens -// // We don't need to do anything here -// } else { -// revert Callback_Swap_InvalidCase(); -// } -// } -// } diff --git a/src/callbacks/liquidity/BaselineV2/README.md b/src/callbacks/liquidity/BaselineV2/README.md deleted file mode 100644 index 4e7f2a7c..00000000 --- a/src/callbacks/liquidity/BaselineV2/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Baseline-Axis Callbacks - -This directory contains a callbacks contract (with allowlist variants) -that launches a Baseline market upon settlement of an Axis auction. - -## Supported Auction Formats - -This callbacks contract currently only supported the Fixed Price Batch auction format. - -## Lifecycle - -1. Deploy Baseline stack - - - The BPOOL module will create a Uniswap V3 pool in the constructor. - As a result, it requires the initial tick of the pool to be - specified as a constructor argument. - The price can be calculated using the following: - - ```solidity - uint256 auctionPrice = 2e18; // Example price - uint160 sqrtPriceX96 = SqrtPriceMath.getSqrtPriceX96( - address(quoteToken), address(BPOOL), auctionPrice, 10 ** baseTokenDecimals - ); - int24 activeTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); - ``` - - - Deploy the Baseline `Kernel`, `BPOOL` module and other policies (except for `BaselineInit`) - -2. Deploy the Baseline-Axis callback - - The `BatchAuctionHouse`, Baseline `Kernel`, quote token (aka reserve) and owner need to be specified as constructor arguments. See the `baselineAllocatedAllowlist-sample.json` file for an example of how to configure this. - - The salt for the callback will need to be generated. See the [salts README](/script/salts/README.md) for instructions. - - Run the deployment script. See the [deployment README](/script/deploy/README.md#running-the-deployment) for instructions. - - Each callbacks contract is single-use, specific to the auction and Baseline stack. -3. Deploy the Axis auction, specifying the callbacks contract and parameters. - - See [TestData.s.sol:createAuction](/script/test/FixedPriceBatch-Baseline/TestData.s.sol) for an example of this. - - Note that curator fees are not supported when using the Baseline-Axis callback. - - `onCreate()` will be called on the callbacks contract. This results in: - - The tick ranges on the Baseline `BPOOL` being configured - - The auction capacity (in terms of `BPOOL` tokens) being minted and transferred to the `BatchAuctionHouse`. -4. When a bid is submitted, if the configured callbacks contract has allowlist functionality, it will determine if the bidder is allowed to bid. -5. On settlement of the auction, the following will happen: - - Any refunded base tokens (`BPOOL` tokens) are burnt - - The configured percentage of proceeds (quote/reserve tokens) are deposited into the floor range of the Baseline pool. - - The remaining proceeds are deposited into the anchor range of the Baseline pool. - - Proportional liquidity (currently 11/10 of the anchor range liquidity) is deployed as `BPOOL` tokens in the discovery range. - - The solvency of the Baseline pool is verified. diff --git a/src/callbacks/liquidity/BaselineV2/lib/IBPOOL.sol b/src/callbacks/liquidity/BaselineV2/lib/IBPOOL.sol deleted file mode 100644 index 8630f38c..00000000 --- a/src/callbacks/liquidity/BaselineV2/lib/IBPOOL.sol +++ /dev/null @@ -1,127 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-only -pragma solidity >=0.8.0; - -import {IUniswapV3Pool} from - "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Pool.sol"; -import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; - -enum Range { - FLOOR, - ANCHOR, - DISCOVERY -} - -struct Ticks { - int24 lower; - int24 upper; -} - -struct Position { - uint128 liquidity; - uint160 sqrtPriceL; - uint160 sqrtPriceU; - uint256 bAssets; - uint256 reserves; - uint256 capacity; -} - -/// @title Baseline's UniswapV3 Liquidity Pool Management Module -/// @dev Imported at commit 88bb34b23b1627207e4c8d3fcd9efad22332eb5f -interface IBPOOLv1 { - //============================================================================================// - // CORE FUNCTIONS // - //============================================================================================// - - // ========= STATE VIEW FUNCTIONS ========== // - - function TICK_SPACING() external view returns (int24); - - function reserve() external view returns (ERC20); - function pool() external view returns (IUniswapV3Pool); - - function getTicks( - Range range_ - ) external view returns (int24 tickLower, int24 tickUpper); - - function getLiquidity( - Range range_ - ) external view returns (uint128); - - // ========= PERMISSIONED WRITE FUNCTIONS ========= // - - function addReservesTo( - Range _range, - uint256 _reserves - ) external returns (uint256 bAssetsAdded_, uint256 reservesAdded_, uint128 liquidityFinal_); - - function addLiquidityTo( - Range _range, - uint128 _liquidity - ) external returns (uint256 bAssetsAdded_, uint256 reservesAdded_, uint128 liquidityFinal_); - - function removeAllFrom( - Range _range - ) - external - returns ( - uint256 bAssetsRemoved_, - uint256 bAssetFees_, - uint256 reservesRemoved_, - uint256 reserveFees_ - ); - - function setTicks(Range _range, int24 _lower, int24 _upper) external; - - /// @notice Mints a set fee to the brs based on the circulating supply. - function mint(address _to, uint256 _amount) external; - - /// @notice Burns excess bAssets not used in the pool POL. - /// @dev No need to discount collateralizedBAssets because it's in a separate contract now. - function burnAllBAssetsInContract() external; - - function setTransferLock( - bool _locked - ) external; - - // ========= PUBLIC READ FUNCTIONS ========= // - - function locked() external view returns (bool); - - /// @notice Returns the price at the lower tick of the floor position - function getBaselineValue() external view returns (uint256); - - /// @notice Returns the closest tick spacing boundary above the active tick - /// Formerly "upperAnchorTick" - function getActiveTS() external view returns (int24 activeTS_); - - /// @notice Wrapper for liquidity data struct - function getPosition( - Range _range - ) external view returns (Position memory position_); - - function getBalancesForLiquidity( - uint160 _sqrtPriceL, - uint160 _sqrtPriceU, - uint128 _liquidity - ) external view returns (uint256 bAssets_, uint256 reserves_); - - function getLiquidityForReserves( - uint160 _sqrtPriceL, - uint160 _sqrtPriceU, - uint256 _reserves, - uint160 _sqrtPriceA - ) external view returns (uint128 liquidity_); - - function getCapacityForLiquidity( - uint160 _sqrtPriceL, - uint160 _sqrtPriceU, - uint128 _liquidity, - uint160 _sqrtPriceA - ) external view returns (uint256 capacity_); - - function getCapacityForReserves( - uint160 _sqrtPriceL, - uint160 _sqrtPriceU, - uint256 _reserves - ) external view returns (uint256 capacity_); -} diff --git a/src/callbacks/liquidity/BaselineV2/lib/ICREDT.sol b/src/callbacks/liquidity/BaselineV2/lib/ICREDT.sol deleted file mode 100644 index cc32ceb3..00000000 --- a/src/callbacks/liquidity/BaselineV2/lib/ICREDT.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; - -import {ERC20} from "@solmate-6.8.0/tokens/ERC20.sol"; - -/// @notice Individual credit account information per user -struct CreditAccount { - uint256 credit; // Used to keep track of data in timeslots - uint256 collateral; // bAsset collateral - uint256 expiry; // Date when credit expires and collateral is defaulted -} - -/// @notice Baseline Credit Module -/// @dev Imported at commit 88bb34b23b1627207e4c8d3fcd9efad22332eb5f -interface ICREDTv1 { - // --- STATE --------------------------------------------------- - - /// @notice bAsset token - function bAsset() external view returns (ERC20); - - /// @notice Individual credit account state - function creditAccounts( - address - ) external view returns (uint256 credit, uint256 collateral, uint256 expiry); - - /// @notice Container for aggregate credit and collateral to be defaulted at a timeslot - struct Defaultable { - uint256 credit; // Total reserves issued for this timeslot - uint256 collateral; // Total bAssets collateralized for this timeslot - } - - /// @notice List of aggregate credits and collateral that must be defaulte when a timeslot is reached - function defaultList( - uint256 - ) external view returns (uint256 credit, uint256 collateral); - - /// @notice Last timeslot that was defaulted, acts as queue iterator - function lastDefaultedTimeslot() external view returns (uint256); - - /// @notice Total reserves issued as credit - function totalCreditIssued() external view returns (uint256); - - /// @notice Total bAssets collateralized - function totalCollateralized() external view returns (uint256); - - /// @notice Total interest accrued - function totalInterestAccumulated() external view returns (uint256); - - // --- EXTERNAL FUNCTIONS -------------------------------------------- - - /// @notice Gets current credit account for user. - /// @dev Returns zeroed account after full repayment or default. - function getCreditAccount( - address _user - ) external view returns (CreditAccount memory account_); - - function updateCreditAccount( - address _user, - uint256 _newCollateral, - uint256 _newCredit, - uint256 _newExpiry - ) external; -} diff --git a/src/callbacks/liquidity/BaselineV2/lib/ILOOPS.sol b/src/callbacks/liquidity/BaselineV2/lib/ILOOPS.sol deleted file mode 100644 index c68f855c..00000000 --- a/src/callbacks/liquidity/BaselineV2/lib/ILOOPS.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; - -/// @notice Baseline LOOPS Module -/// @dev Imported at commit 8950018baec27d6497fba409cb361a596535447d -interface ILOOPSv1 { - function totalDebt() external view returns (uint256); -} diff --git a/src/callbacks/liquidity/BaselineV2/lib/Kernel.sol b/src/callbacks/liquidity/BaselineV2/lib/Kernel.sol deleted file mode 100644 index 855fef07..00000000 --- a/src/callbacks/liquidity/BaselineV2/lib/Kernel.sol +++ /dev/null @@ -1,438 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-only -pragma solidity ^0.8.0; - -//============================================================================================// -// GLOBAL TYPES // -//============================================================================================// - -/// @notice Actions to trigger state changes in the kernel. Passed by the executor -enum Actions { - InstallModule, - UpgradeModule, - ActivatePolicy, - DeactivatePolicy, - ChangeExecutor, - MigrateKernel -} - -/// @notice Used by executor to select an action and a target contract for a kernel action -struct Instruction { - Actions action; - address target; -} - -/// @notice Used to define which module functions a policy needs access to -struct Permissions { - Keycode keycode; - bytes4 funcSelector; -} - -type Keycode is bytes5; - -//============================================================================================// -// UTIL FUNCTIONS // -//============================================================================================// - -error TargetNotAContract(address target_); -error InvalidKeycode(Keycode keycode_); - -function toKeycode( - bytes5 keycode_ -) pure returns (Keycode) { - return Keycode.wrap(keycode_); -} - -function fromKeycode( - Keycode keycode_ -) pure returns (bytes5) { - return Keycode.unwrap(keycode_); -} - -function ensureContract( - address target_ -) view { - if (target_.code.length == 0) revert TargetNotAContract(target_); -} - -function ensureValidKeycode( - Keycode keycode_ -) pure { - bytes5 unwrapped = Keycode.unwrap(keycode_); - for (uint256 i = 0; i < 5;) { - bytes1 char = unwrapped[i]; - if (char < 0x41 || char > 0x5A) revert InvalidKeycode(keycode_); // A-Z only - unchecked { - i++; - } - } -} - -//============================================================================================// -// COMPONENTS // -//============================================================================================// - -/// @notice Generic adapter interface for kernel access in modules and policies. -abstract contract KernelAdapter { - error KernelAdapter_OnlyKernel(address caller_); - - Kernel public kernel; - - constructor( - Kernel kernel_ - ) { - kernel = kernel_; - } - - /// @notice Modifier to restrict functions to be called only by kernel. - modifier onlyKernel() { - if (msg.sender != address(kernel)) revert KernelAdapter_OnlyKernel(msg.sender); - _; - } - - /// @notice Function used by kernel when migrating to a new kernel. - function changeKernel( - Kernel newKernel_ - ) external onlyKernel { - kernel = newKernel_; - } -} - -/// @notice Base level extension of the kernel. Modules act as independent state components to be -/// interacted with and mutated through policies. -/// @dev Modules are installed and uninstalled via the executor. -abstract contract Module is KernelAdapter { - error Module_PolicyNotPermitted(address policy_); - - constructor( - Kernel kernel_ - ) KernelAdapter(kernel_) {} - - /// @notice Modifier to restrict which policies have access to module functions. - modifier permissioned() { - if ( - msg.sender == address(kernel) - || !kernel.modulePermissions(KEYCODE(), Policy(msg.sender), msg.sig) - ) revert Module_PolicyNotPermitted(msg.sender); - _; - } - - /// @notice 5 byte identifier for a module. - function KEYCODE() public pure virtual returns (Keycode) {} - - /// @notice Returns which semantic version of a module is being implemented. - /// @return major - Major version upgrade indicates breaking change to the interface. - /// @return minor - Minor version change retains backward-compatible interface. - function VERSION() external pure virtual returns (uint8 major, uint8 minor) {} - - /// @notice Initialization function for the module - /// @dev This function is called when the module is installed or upgraded by the kernel. - /// @dev MUST BE GATED BY onlyKernel. Used to encompass any initialization or upgrade logic. - function INIT() external virtual onlyKernel {} -} - -/// @notice Policies are application logic and external interface for the kernel and installed modules. -/// @dev Policies are activated and deactivated in the kernel by the executor. -/// @dev Module dependencies and function permissions must be defined in appropriate functions. -abstract contract Policy is KernelAdapter { - error Policy_ModuleDoesNotExist(Keycode keycode_); - error Policy_WrongModuleVersion(bytes expected_); - - constructor( - Kernel kernel_ - ) KernelAdapter(kernel_) {} - - /// @notice Easily accessible indicator for if a policy is activated or not. - function isActive() external view returns (bool) { - return kernel.isPolicyActive(this); - } - - /// @notice Function to grab module address from a given keycode. - function getModuleAddress( - Keycode keycode_ - ) internal view returns (address) { - address moduleForKeycode = address(kernel.getModuleForKeycode(keycode_)); - if (moduleForKeycode == address(0)) revert Policy_ModuleDoesNotExist(keycode_); - return moduleForKeycode; - } - - /// @notice Define module dependencies for this policy. - /// @return dependencies - Keycode array of module dependencies. - function configureDependencies() external virtual returns (Keycode[] memory dependencies) {} - - /// @notice Function called by kernel to set module function permissions. - /// @return requests - Array of keycodes and function selectors for requested permissions. - function requestPermissions() external view virtual returns (Permissions[] memory requests) {} -} - -/// @notice Main contract that acts as a central component registry for the protocol. -/// @dev The kernel manages modules and policies. The kernel is mutated via predefined Actions, -/// @dev which are input from any address assigned as the executor. The executor can be changed as needed. -contract Kernel { - // ========= EVENTS ========= // - - event PermissionsUpdated( - Keycode indexed keycode_, Policy indexed policy_, bytes4 funcSelector_, bool granted_ - ); - event ActionExecuted(Actions indexed action_, address indexed target_); - - // ========= ERRORS ========= // - - error Kernel_OnlyExecutor(address caller_); - error Kernel_ModuleAlreadyInstalled(Keycode module_); - error Kernel_InvalidModuleUpgrade(Keycode module_); - error Kernel_PolicyAlreadyActivated(address policy_); - error Kernel_PolicyNotActivated(address policy_); - - // ========= PRIVILEGED ADDRESSES ========= // - - /// @notice Address that is able to initiate Actions in the kernel. Can be assigned to a multisig or governance contract. - address public executor; - - // ========= MODULE MANAGEMENT ========= // - - /// @notice Array of all modules currently installed. - Keycode[] public allKeycodes; - - /// @notice Mapping of module address to keycode. - mapping(Keycode => Module) public getModuleForKeycode; - - /// @notice Mapping of keycode to module address. - mapping(Module => Keycode) public getKeycodeForModule; - - /// @notice Mapping of a keycode to all of its policy dependents. Used to efficiently reconfigure policy dependencies. - mapping(Keycode => Policy[]) public moduleDependents; - - /// @notice Helper for module dependent arrays. Prevents the need to loop through array. - mapping(Keycode => mapping(Policy => uint256)) public getDependentIndex; - - /// @notice Module <> Policy Permissions. - /// @dev Keycode -> Policy -> Function Selector -> bool for permission - mapping(Keycode => mapping(Policy => mapping(bytes4 => bool))) public modulePermissions; - - // ========= POLICY MANAGEMENT ========= // - - /// @notice List of all active policies - Policy[] public activePolicies; - - /// @notice Helper to get active policy quickly. Prevents need to loop through array. - mapping(Policy => uint256) public getPolicyIndex; - - //============================================================================================// - // CORE FUNCTIONS // - //============================================================================================// - - constructor() { - executor = msg.sender; - } - - /// @notice Modifier to check if caller is the executor. - modifier onlyExecutor() { - if (msg.sender != executor) revert Kernel_OnlyExecutor(msg.sender); - _; - } - - function isPolicyActive( - Policy policy_ - ) public view returns (bool) { - return activePolicies.length > 0 && activePolicies[getPolicyIndex[policy_]] == policy_; - } - - /// @notice Main kernel function. Initiates state changes to kernel depending on Action passed in. - function executeAction(Actions action_, address target_) external onlyExecutor { - if (action_ == Actions.InstallModule) { - ensureContract(target_); - ensureValidKeycode(Module(target_).KEYCODE()); - _installModule(Module(target_)); - } else if (action_ == Actions.UpgradeModule) { - ensureContract(target_); - ensureValidKeycode(Module(target_).KEYCODE()); - _upgradeModule(Module(target_)); - } else if (action_ == Actions.ActivatePolicy) { - ensureContract(target_); - _activatePolicy(Policy(target_)); - } else if (action_ == Actions.DeactivatePolicy) { - ensureContract(target_); - _deactivatePolicy(Policy(target_)); - } else if (action_ == Actions.ChangeExecutor) { - executor = target_; - } else if (action_ == Actions.MigrateKernel) { - ensureContract(target_); - _migrateKernel(Kernel(target_)); - } - - emit ActionExecuted(action_, target_); - } - - function _installModule( - Module newModule_ - ) internal { - Keycode keycode = newModule_.KEYCODE(); - - if (address(getModuleForKeycode[keycode]) != address(0)) { - revert Kernel_ModuleAlreadyInstalled(keycode); - } - - getModuleForKeycode[keycode] = newModule_; - getKeycodeForModule[newModule_] = keycode; - allKeycodes.push(keycode); - - newModule_.INIT(); - } - - function _upgradeModule( - Module newModule_ - ) internal { - Keycode keycode = newModule_.KEYCODE(); - Module oldModule = getModuleForKeycode[keycode]; - - if (address(oldModule) == address(0) || oldModule == newModule_) { - revert Kernel_InvalidModuleUpgrade(keycode); - } - - getKeycodeForModule[oldModule] = Keycode.wrap(bytes5(0)); - getKeycodeForModule[newModule_] = keycode; - getModuleForKeycode[keycode] = newModule_; - - newModule_.INIT(); - - _reconfigurePolicies(keycode); - } - - function _activatePolicy( - Policy policy_ - ) internal { - if (isPolicyActive(policy_)) revert Kernel_PolicyAlreadyActivated(address(policy_)); - - // Add policy to list of active policies - activePolicies.push(policy_); - getPolicyIndex[policy_] = activePolicies.length - 1; - - // Record module dependencies - Keycode[] memory dependencies = policy_.configureDependencies(); - uint256 depLength = dependencies.length; - - for (uint256 i; i < depLength;) { - Keycode keycode = dependencies[i]; - - moduleDependents[keycode].push(policy_); - getDependentIndex[keycode][policy_] = moduleDependents[keycode].length - 1; - - unchecked { - ++i; - } - } - - // Grant permissions for policy to access restricted module functions - Permissions[] memory requests = policy_.requestPermissions(); - _setPolicyPermissions(policy_, requests, true); - } - - function _deactivatePolicy( - Policy policy_ - ) internal { - if (!isPolicyActive(policy_)) revert Kernel_PolicyNotActivated(address(policy_)); - - // Revoke permissions - Permissions[] memory requests = policy_.requestPermissions(); - _setPolicyPermissions(policy_, requests, false); - - // Remove policy from all policy data structures - uint256 idx = getPolicyIndex[policy_]; - Policy lastPolicy = activePolicies[activePolicies.length - 1]; - - activePolicies[idx] = lastPolicy; - activePolicies.pop(); - getPolicyIndex[lastPolicy] = idx; - delete getPolicyIndex[policy_]; - - // Remove policy from module dependents - _pruneFromDependents(policy_); - } - - /// @notice All functionality will move to the new kernel. WARNING: ACTION WILL BRICK THIS KERNEL. - /// @dev New kernel must add in all of the modules and policies via executeAction. - /// @dev NOTE: Data does not get cleared from this kernel. - function _migrateKernel( - Kernel newKernel_ - ) internal { - uint256 keycodeLen = allKeycodes.length; - for (uint256 i; i < keycodeLen;) { - Module module = Module(getModuleForKeycode[allKeycodes[i]]); - module.changeKernel(newKernel_); - unchecked { - ++i; - } - } - - uint256 policiesLen = activePolicies.length; - for (uint256 j; j < policiesLen;) { - Policy policy = activePolicies[j]; - - // Deactivate before changing kernel - policy.changeKernel(newKernel_); - unchecked { - ++j; - } - } - } - - function _reconfigurePolicies( - Keycode keycode_ - ) internal { - Policy[] memory dependents = moduleDependents[keycode_]; - uint256 depLength = dependents.length; - - for (uint256 i; i < depLength;) { - dependents[i].configureDependencies(); - - unchecked { - ++i; - } - } - } - - function _setPolicyPermissions( - Policy policy_, - Permissions[] memory requests_, - bool grant_ - ) internal { - uint256 reqLength = requests_.length; - for (uint256 i = 0; i < reqLength;) { - Permissions memory request = requests_[i]; - modulePermissions[request.keycode][policy_][request.funcSelector] = grant_; - - emit PermissionsUpdated(request.keycode, policy_, request.funcSelector, grant_); - - unchecked { - ++i; - } - } - } - - function _pruneFromDependents( - Policy policy_ - ) internal { - Keycode[] memory dependencies = policy_.configureDependencies(); - uint256 depcLength = dependencies.length; - - for (uint256 i; i < depcLength;) { - Keycode keycode = dependencies[i]; - Policy[] storage dependents = moduleDependents[keycode]; - - uint256 origIndex = getDependentIndex[keycode][policy_]; - Policy lastPolicy = dependents[dependents.length - 1]; - - // Swap with last and pop - dependents[origIndex] = lastPolicy; - dependents.pop(); - - // Record new index and delete deactivated policy index - getDependentIndex[keycode][lastPolicy] = origIndex; - delete getDependentIndex[keycode][policy_]; - - unchecked { - ++i; - } - } - } -} diff --git a/test/Constants.sol b/test/Constants.sol index 2be22ab7..9f0f156e 100644 --- a/test/Constants.sol +++ b/test/Constants.sol @@ -6,9 +6,6 @@ import {TestConstants as TestConstantsCore} from "@axis-core-1.0.4-test/Constant abstract contract TestConstants is TestConstantsCore { address internal constant _UNISWAP_V3_FACTORY = address(0xAAB5b268B35f9e63c0D88EEfacC89785cC3077d4); - // address internal constant _BASELINE_KERNEL = address(0xBB); - // address internal constant _BASELINE_QUOTE_TOKEN = - // address(0xAABA4a4ef5c3C62a3F40e61BC675331662dB4D96); address internal constant _CREATE2_DEPLOYER = address(0x4e59b44847b379578588920cA78FbF26c0B4956C); diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol deleted file mode 100644 index bdf93f04..00000000 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/BaselineAllocatedAllowlistTest.sol +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Test scaffolding -import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; - -// Axis -import {BALwithAllocatedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; - -// Baseline -import {Actions as BaselineKernelActions} from "@baseline/Kernel.sol"; - -contract BaselineAllocatedAllowlistTest is BaselineAxisLaunchTest { - // ========== MODIFIERS ========== // - - modifier givenCallbackIsCreated() override { - // Get the salt - bytes memory args = - abi.encode(address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - bytes32 salt = _getTestSalt( - "BaselineAllocatedAllowlist", type(BALwithAllocatedAllowlist).creationCode, args - ); - - // Required for CREATE2 address to work correctly. doesn't do anything in a test - // Source: https://github.com/foundry-rs/foundry/issues/6402 - vm.startBroadcast(); - _dtl = new BALwithAllocatedAllowlist{salt: salt}( - address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER - ); - vm.stopBroadcast(); - - _dtlAddress = address(_dtl); - - // Install as a policy - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, _dtlAddress); - _; - } - - modifier givenAllowlistParams( - bytes32 merkleRoot_ - ) { - _createData.allowlistParams = abi.encode(merkleRoot_); - _; - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol deleted file mode 100644 index f14e2e48..00000000 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onBid.t.sol +++ /dev/null @@ -1,248 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BALwithAllocatedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; - -contract BaselineAllocatedAllowlistOnBidTest is BaselineAllocatedAllowlistTest { - // Use the @openzeppelin/merkle-tree package or the scripts in axis-utils to generate the merkle tree - - // Values: - // 0x0000000000000000000000000000000000000004, 5e18 - // 0x0000000000000000000000000000000000000020, 0 - bytes32 internal constant _MERKLE_ROOT = - 0x0fdc3942d9af344db31ff2e80c06bc4e558dc967ca5b4d421d741870f5ea40df; - bytes32 internal constant _BUYER_MERKLE_PROOF = - 0x2eac7b0cadd960cd4457012a5e232aa3532d9365ba6df63c1b5a9c7846f77760; - bytes32 internal constant _NOT_SELLER_MERKLE_PROOF = - 0xe0a73973cd60d8cbabb978d1f3c983065148b388619b9176d3d30e47c16d4fd5; - - bytes32[] internal _proof; - uint256 internal _allocatedAmount; - - uint64 internal constant _BID_ID = 1; - - // ========== MODIFIER ========== // - - modifier givenMerkleProof( - bytes32 merkleProof_ - ) { - bytes32[] memory proof = new bytes32[](1); - proof[0] = merkleProof_; - - _proof = proof; - _; - } - - modifier givenMerkleAllocatedAmount( - uint256 allocatedAmount_ - ) { - _allocatedAmount = allocatedAmount_; - _; - } - - function _onBid( - uint256 bidAmount_ - ) internal { - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, bidAmount_, abi.encode(_proof, _allocatedAmount)); - } - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the merkle proof is invalid - // [X] it reverts - // [X] when the buyer is not in the merkle tree - // [X] it reverts - // [X] when the buyer has already spent their limit - // [X] it reverts - // [X] when the buyer has a 0 limit - // [X] it reverts - // [X] when the buyer has not made a bid - // [X] when the bid amount is over the buyer's limit - // [X] it reverts - // [X] it updates the spent amount with the bid amount - // [X] when the bid amount is over the remaining limit - // [X] it reverts - // [X] it updates the spent amount with the bid amount - - function test_parametersInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Expect revert - vm.expectRevert(); - - // Call the callback with an invalid parameter format - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, 5e18, abi.encode(uint256(20), bytes("something"))); - } - - function test_merkleProofInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_NOT_SELLER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) // Amount is different to what is in the merkle tree - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback with an invalid merkle proof - _onBid(5e18); - } - - function test_buyerNotInMerkleTree_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, address(0x55), 5e18, abi.encode(_proof, _allocatedAmount)); - } - - function test_buyerLimitSpent_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Spend the allocation - _onBid(5e18); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback again - _onBid(1e18); - } - - function test_buyerZeroLimit_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_NOT_SELLER_MERKLE_PROOF) - givenMerkleAllocatedAmount(0) - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _NOT_SELLER, 5e18, abi.encode(_proof, _allocatedAmount)); - } - - function test_noBids_aboveLimit_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback - _onBid(6e18); - } - - function test_noBids_belowLimit() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Call the callback - _onBid(4e18); - - // Check the buyer spent amount - assertEq(BALwithAllocatedAllowlist(address(_dtl)).buyerSpent(_BUYER), 4e18, "buyer spent"); - } - - function test_remainingLimit_aboveLimit_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Spend the allocation - _onBid(4e18); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback again - _onBid(2e18); - } - - function test_remainingLimit_belowLimit() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - givenMerkleAllocatedAmount(5e18) - { - // Spend the allocation - _onBid(4e18); - - // Call the callback - _onBid(1e18); - - // Check the buyer spent amount - assertEq(BALwithAllocatedAllowlist(address(_dtl)).buyerSpent(_BUYER), 5e18, "buyer spent"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol deleted file mode 100644 index 3edf9fb5..00000000 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/onCreate.t.sol +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BALwithAllocatedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; - -contract BaselineAllocatedAllowlistOnCreateTest is BaselineAllocatedAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the seller is not the owner - // [X] it reverts - // [X] it decodes and stores the merkle root - - function test_allowlistParamsIncorrect_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the allowlist parameters to be an incorrect format - _createData.allowlistParams = abi.encode(uint256(20), bytes32("hello")); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_sellerNotOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(_OWNER); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Call the callback - _onCreate(); - - // Check the merkle root is stored - assertEq(BALwithAllocatedAllowlist(address(_dtl)).merkleRoot(), _MERKLE_ROOT, "merkle root"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol deleted file mode 100644 index a321c51f..00000000 --- a/test/callbacks/liquidity/BaselineV2/AllocatedAllowlist/setMerkleRoot.t.sol +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllocatedAllowlistTest} from "./BaselineAllocatedAllowlistTest.sol"; - -import {BALwithAllocatedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllocatedAllowlist.sol"; - -contract BaselineAllocatedAllowlistSetMerkleRootTest is BaselineAllocatedAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - bytes32 internal constant _NEW_MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - function _setMerkleRoot() internal { - vm.prank(_SELLER); - BALwithAllocatedAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - // ========== TESTS ========== // - - // [X] when the caller is not the owner - // [X] it reverts - // [X] when the auction has not been registered - // [X] it reverts - // [X] when the auction has been completed - // [X] it reverts - // [X] the merkle root is updated and an event is emitted - - function test_notOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Expect revert - vm.expectRevert("UNAUTHORIZED"); - - // Call the callback - BALwithAllocatedAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - function test_auctionNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_auctionCompleted_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform onSettle callback - _onSettle(); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithAllocatedAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Call the callback - _setMerkleRoot(); - - // Check the merkle root is updated - assertEq( - BALwithAllocatedAllowlist(address(_dtl)).merkleRoot(), _NEW_MERKLE_ROOT, "merkle root" - ); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol deleted file mode 100644 index 87f8f15f..00000000 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/BaselineAllowlistTest.sol +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Test scaffolding -import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; - -// Axis -import {BALwithAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; - -// Baseline -import {Actions as BaselineKernelActions} from "@baseline/Kernel.sol"; - -contract BaselineAllowlistTest is BaselineAxisLaunchTest { - uint256 internal constant _BUYER_LIMIT = 5e18; - - // ========== MODIFIERS ========== // - - modifier givenCallbackIsCreated() override { - // Get the salt - bytes memory args = - abi.encode(address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - bytes32 salt = _getTestSalt("BaselineAllowlist", type(BALwithAllowlist).creationCode, args); - - // Required for CREATE2 address to work correctly. doesn't do anything in a test - // Source: https://github.com/foundry-rs/foundry/issues/6402 - vm.startBroadcast(); - _dtl = new BALwithAllowlist{salt: salt}( - address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER - ); - vm.stopBroadcast(); - - _dtlAddress = address(_dtl); - - // Install as a policy - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, _dtlAddress); - _; - } - - modifier givenAllowlistParams( - bytes32 merkleRoot_ - ) { - _createData.allowlistParams = abi.encode(merkleRoot_); - _; - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol deleted file mode 100644 index 29447f25..00000000 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/onBid.t.sol +++ /dev/null @@ -1,123 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; - -contract BaselineAllowlistOnBidTest is BaselineAllowlistTest { - // Use the @openzeppelin/merkle-tree package or the scripts in axis-utils to generate the merkle tree - - // Values: - // 0x0000000000000000000000000000000000000004 - // 0x0000000000000000000000000000000000000005 - bytes32 internal constant _MERKLE_ROOT = - 0xc92348ba87c65979cc4f264810321a35efa64e795075908af2c507a22d4da472; - bytes32 internal constant _BUYER_MERKLE_PROOF = - 0x16db2e4b9f8dc120de98f8491964203ba76de27b27b29c2d25f85a325cd37477; - bytes32 internal constant _NOT_SELLER_MERKLE_PROOF = - 0xc167b0e3c82238f4f2d1a50a8b3a44f96311d77b148c30dc0ef863e1a060dcb6; - - bytes32[] internal _proof; - - uint64 internal constant _BID_ID = 1; - - // ========== MODIFIER ========== // - - modifier givenMerkleProof( - bytes32 merkleProof_ - ) { - bytes32[] memory proof = new bytes32[](1); - proof[0] = merkleProof_; - - _proof = proof; - _; - } - - function _onBid( - uint256 bidAmount_ - ) internal { - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, bidAmount_, abi.encode(_proof)); - } - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the merkle proof is invalid - // [X] it reverts - // [X] when the buyer is not in the merkle tree - // [X] it reverts - // [X] it succeeds - - function test_parametersInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Expect revert - vm.expectRevert(); - - // Call the callback with an invalid parameter format - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, 5e18, abi.encode(uint256(20), bytes("something"))); - } - - function test_merkleProofInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_NOT_SELLER_MERKLE_PROOF) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback with an invalid merkle proof - _onBid(5e18); - } - - function test_buyerNotInMerkleTree_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, address(0x55), 5e18, abi.encode(_proof)); - } - - function test_success( - uint256 bidAmount_ - ) - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Call the callback - _onBid(bidAmount_); - - // Does not revert - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol deleted file mode 100644 index 86cfd7b0..00000000 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/onCreate.t.sol +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BALwithAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; - -contract BaselineAllowlistOnCreateTest is BaselineAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the seller is not the owner - // [X] it reverts - // [X] it decodes and stores the merkle root - - function test_allowlistParamsIncorrect_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the allowlist parameters to be an incorrect format - _createData.allowlistParams = abi.encode(uint256(20), bytes32("hello"), uint256(10)); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_sellerNotOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(_OWNER); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Call the callback - _onCreate(); - - // Check the merkle root is stored - assertEq(BALwithAllowlist(address(_dtl)).merkleRoot(), _MERKLE_ROOT, "merkle root"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol deleted file mode 100644 index e0d5d15b..00000000 --- a/test/callbacks/liquidity/BaselineV2/Allowlist/setMerkleRoot.t.sol +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAllowlistTest} from "./BaselineAllowlistTest.sol"; - -import {BALwithAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; - -contract BaselineAllowlistSetMerkleRootTest is BaselineAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - bytes32 internal constant _NEW_MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - function _setMerkleRoot() internal { - vm.prank(_SELLER); - BALwithAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - // ========== TESTS ========== // - - // [X] when the caller is not the owner - // [X] it reverts - // [X] when the auction has not been registered - // [X] it reverts - // [X] when the auction has been completed - // [X] it reverts - // [X] the merkle root is updated and an event is emitted - - function test_notOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Expect revert - vm.expectRevert("UNAUTHORIZED"); - - // Call the callback - BALwithAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - function test_auctionNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BALwithAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_auctionCompleted_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform onSettle callback - _onSettle(); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BALwithAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT) - givenOnCreate - { - // Call the callback - _setMerkleRoot(); - - // Check the merkle root is updated - assertEq(BALwithAllowlist(address(_dtl)).merkleRoot(), _NEW_MERKLE_ROOT, "merkle root"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol b/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol deleted file mode 100644 index 7dd36bdb..00000000 --- a/test/callbacks/liquidity/BaselineV2/BPOOLMinter.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; - -import {Kernel, Keycode, toKeycode, Policy, Permissions} from "@baseline/Kernel.sol"; -import {BPOOLv1} from "@baseline/modules/BPOOL.v1.sol"; -import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; - -contract BPOOLMinter is Policy, Owned { - // solhint-disable var-name-mixedcase - BPOOLv1 public BPOOL; - CREDTv1 public CREDT; - // solhint-enable var-name-mixedcase - - constructor( - Kernel kernel_ - ) Policy(kernel_) Owned(kernel_.executor()) {} - - function configureDependencies() external override returns (Keycode[] memory dependencies) { - dependencies = new Keycode[](2); - dependencies[0] = toKeycode("BPOOL"); - dependencies[1] = toKeycode("CREDT"); - - BPOOL = BPOOLv1(getModuleAddress(toKeycode("BPOOL"))); - CREDT = CREDTv1(getModuleAddress(toKeycode("CREDT"))); - } - - function requestPermissions() external view override returns (Permissions[] memory requests) { - requests = new Permissions[](3); - requests[0] = Permissions(toKeycode("BPOOL"), BPOOL.mint.selector); - requests[1] = Permissions(toKeycode("BPOOL"), BPOOL.setTransferLock.selector); - requests[2] = Permissions(toKeycode("CREDT"), CREDT.updateCreditAccount.selector); - } - - function mint(address to_, uint256 amount_) external onlyOwner { - BPOOL.mint(to_, amount_); - } - - function setTransferLock( - bool lock_ - ) external onlyOwner { - BPOOL.setTransferLock(lock_); - } - - /// @notice Mimics allocating credit (call options) to a user - function allocateCreditAccount(address user_, uint256 amount_, uint256 days_) external { - // Transfer collateral - BPOOL.transferFrom(user_, address(this), amount_); - - // Calculate the amount of debt to record against the collateral - uint256 debt = amount_ * BPOOL.getBaselineValue() / 1e18; - - // Approve spending - BPOOL.approve(address(CREDT), amount_); - - // Update credit account - CREDT.updateCreditAccount(user_, amount_, debt, block.timestamp + days_ * 1 days); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol b/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol deleted file mode 100644 index 08bf1c2f..00000000 --- a/test/callbacks/liquidity/BaselineV2/BaselineAxisLaunchTest.sol +++ /dev/null @@ -1,762 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Test scaffolding -import {Test} from "@forge-std-1.9.1/Test.sol"; -import {console2} from "@forge-std-1.9.1/console2.sol"; -import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; -import {WithSalts} from "../../../lib/WithSalts.sol"; -import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -import {IUniswapV3Factory} from - "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Factory.sol"; -import {UniswapV3Factory} from "../../../lib/uniswap-v3/UniswapV3Factory.sol"; -import {ComputeAddress} from "../../../lib/ComputeAddress.sol"; -import {FixedPointMathLib} from "@solmate-6.8.0/utils/FixedPointMathLib.sol"; -import {TestConstants} from "../../../Constants.sol"; -import {SqrtPriceMath} from "../../../../src/lib/uniswap-v3/SqrtPriceMath.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; - -// Axis core -import {IAuction} from "@axis-core-1.0.4/interfaces/modules/IAuction.sol"; -import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; -import {BatchAuctionHouse} from "@axis-core-1.0.4/BatchAuctionHouse.sol"; -import {EncryptedMarginalPrice} from "@axis-core-1.0.4/modules/auctions/batch/EMP.sol"; -import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; -import {FixedPriceBatch} from "@axis-core-1.0.4/modules/auctions/batch/FPB.sol"; - -// Callbacks -import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; -import {BaselineAxisLaunch} from - "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; - -// Baseline -import {Kernel as BaselineKernel, Actions as BaselineKernelActions} from "@baseline/Kernel.sol"; -import {BPOOLv1, Range, Position} from "@baseline/modules/BPOOL.v1.sol"; -import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; -import {LOOPSv1} from "@baseline/modules/LOOPS.v1.sol"; -import {MarketMaking} from "@baseline/policies/MarketMaking.sol"; -import {BPOOLMinter} from "./BPOOLMinter.sol"; -import {MockBlast} from "./MockBlast.sol"; - -// solhint-disable max-states-count - -abstract contract BaselineAxisLaunchTest is Test, Permit2User, WithSalts, TestConstants { - using Callbacks for BaselineAxisLaunch; - - address internal constant _PROTOCOL = address(0x3); - address internal constant _BUYER = address(0x4); - address internal constant _BORROWER = address(0x10); - address internal constant _NOT_SELLER = address(0x20); - - uint24 internal constant _ONE_HUNDRED_PERCENT = 100e2; - - uint96 internal constant _LOT_CAPACITY = 10e18; - uint96 internal constant _REFUND_AMOUNT = 2e18; - uint256 internal constant _PROCEEDS_AMOUNT = 24e18; - int24 internal constant _ANCHOR_TICK_WIDTH = 10; - int24 internal constant _DISCOVERY_TICK_WIDTH = 350; - uint24 internal constant _FLOOR_RESERVES_PERCENT = 50e2; // 50% - uint24 internal constant _POOL_PERCENT = 87e2; // 87% - uint256 internal constant _FIXED_PRICE = 3e18; - int24 internal constant _FIXED_PRICE_TICK_UPPER = 11_000; // 10986 rounded up - int24 internal constant _POOL_TARGET_TICK = 10_986; // 10986 being the default - uint256 internal constant _INITIAL_POOL_PRICE = 3e18; // 3 - uint24 internal constant _FEE_TIER = 10_000; - uint256 internal constant _BASE_SCALE = 1e18; - uint8 internal _quoteTokenDecimals = 18; - uint8 internal _baseTokenDecimals = 18; - bool internal _isBaseTokenAddressLower = true; - /// @dev Set in `givenBPoolFeeTier()` - uint24 internal _feeTier = _FEE_TIER; - /// @dev Set in `_setPoolInitialTickFromAuctionPrice()` - int24 internal _poolInitialTick; - /// @dev Set in `_setFloorRangeGap()` - int24 internal _floorRangeGap; - uint48 internal _protocolFeePercent; - uint256 internal _protocolFee; - uint48 internal _referrerFeePercent; - uint256 internal _referrerFee; - uint48 internal _curatorFeePercent; - uint256 internal _curatorFee; - - uint256 internal _proceeds = _PROCEEDS_AMOUNT; - uint256 internal _refund = _REFUND_AMOUNT; - - uint48 internal constant _START = 1_000_000; - - uint96 internal _lotId = 1; - - BatchAuctionHouse internal _auctionHouse; - EncryptedMarginalPrice internal _empModule; - FixedPriceBatch internal _fpbModule; - BaselineAxisLaunch internal _dtl; - address internal _dtlAddress; - IUniswapV3Factory internal _uniV3Factory; - - int24 internal _tickSpacing; - - IAuction internal _auctionModule; - - MockERC20 internal _quoteToken; - BaselineKernel internal _baselineKernel; - BPOOLv1 internal _baseToken; - CREDTv1 internal _creditModule; - LOOPSv1 internal _loopsModule; - MarketMaking internal _marketMaking; - BPOOLMinter internal _bPoolMinter; - MockBlast internal _blast; - address internal _blastGovernor; - - // Inputs - IFixedPriceBatch.AuctionDataParams internal _fpbParams = IFixedPriceBatch.AuctionDataParams({ - price: _FIXED_PRICE, - minFillPercent: 50e2 // 50% - }); - - BaselineAxisLaunch.CreateData internal _createData = BaselineAxisLaunch.CreateData({ - recipient: _SELLER, - poolPercent: _POOL_PERCENT, - floorReservesPercent: _FLOOR_RESERVES_PERCENT, - floorRangeGap: _floorRangeGap, - anchorTickU: _FIXED_PRICE_TICK_UPPER, - anchorTickWidth: _ANCHOR_TICK_WIDTH, - poolTargetTick: _POOL_TARGET_TICK, - allowlistParams: abi.encode("") - }); - - function setUp() public { - // Set reasonable timestamp - vm.warp(_START); - - // Create an BatchAuctionHouse at a deterministic address, since it is used as input to callbacks - BatchAuctionHouse auctionHouse = new BatchAuctionHouse(_OWNER, _PROTOCOL, _permit2Address); - _auctionHouse = BatchAuctionHouse(_AUCTION_HOUSE); - vm.etch(address(_auctionHouse), address(auctionHouse).code); - vm.store(address(_auctionHouse), bytes32(uint256(0)), bytes32(abi.encode(_OWNER))); // Owner - vm.store(address(_auctionHouse), bytes32(uint256(6)), bytes32(abi.encode(1))); // Reentrancy - vm.store(address(_auctionHouse), bytes32(uint256(10)), bytes32(abi.encode(_PROTOCOL))); // Protocol - - // Create a UniswapV3Factory at a deterministic address - vm.startBroadcast(); - bytes32 uniswapV3Salt = - _getTestSalt("UniswapV3Factory", type(UniswapV3Factory).creationCode, abi.encode()); - _uniV3Factory = new UniswapV3Factory{salt: uniswapV3Salt}(); - vm.stopBroadcast(); - if (address(_uniV3Factory) != _UNISWAP_V3_FACTORY) { - console2.log("UniswapV3Factory address: ", address(_uniV3Factory)); - revert("UniswapV3Factory address mismatch"); - } - - // Create the Baseline kernel at a deterministic address, since it is used as input to callbacks - vm.prank(_OWNER); - BaselineKernel baselineKernel = new BaselineKernel(); - _baselineKernel = BaselineKernel(_BASELINE_KERNEL); - vm.etch(address(_baselineKernel), address(baselineKernel).code); - vm.store(address(_baselineKernel), bytes32(uint256(0)), bytes32(abi.encode(_OWNER))); // Owner - - // Create auction modules - _empModule = new EncryptedMarginalPrice(address(_auctionHouse)); - _fpbModule = new FixedPriceBatch(address(_auctionHouse)); - - // Default auction module is FPB - _auctionModule = _fpbModule; - _mockGetAuctionModuleForId(); - - // Create the quote token at a deterministic address - bytes32 quoteTokenSalt = _getTestSalt( - "QuoteToken", type(MockERC20).creationCode, abi.encode("Quote Token", "QT", 18) - ); - vm.prank(_CREATE2_DEPLOYER); - _quoteToken = new MockERC20{salt: quoteTokenSalt}("Quote Token", "QT", 18); - _quoteTokenDecimals = 18; - if (address(_quoteToken) != _BASELINE_QUOTE_TOKEN) { - console2.log("Quote Token address: ", address(_quoteToken)); - revert("Quote Token address mismatch"); - } - - _tickSpacing = _uniV3Factory.feeAmountTickSpacing(_feeTier); - console2.log("Tick spacing: ", _tickSpacing); - - _blast = new MockBlast(); - - // Set up Baseline - _creditModule = new CREDTv1(_baselineKernel, address(_blast), _blastGovernor); - _loopsModule = new LOOPSv1(_baselineKernel, 1e18); - _marketMaking = new MarketMaking( - _baselineKernel, 25, 1000, 3e18, address(0), address(_blast), _blastGovernor - ); - // Base token is created in the givenBPoolIsCreated modifier - _bPoolMinter = new BPOOLMinter(_baselineKernel); - - // Calculate the initial tick - _setPoolInitialTickFromPrice(_INITIAL_POOL_PRICE); - } - - // ========== MODIFIERS ========== // - - function _setPoolInitialTickFromTick( - int24 tick_ - ) internal { - _poolInitialTick = tick_; - console2.log("Pool initial tick (using tick) set to: ", _poolInitialTick); - } - - function _setPoolInitialTickFromPrice( - uint256 price_ - ) internal { - _poolInitialTick = _getTickFromPrice(price_, _baseTokenDecimals, _isBaseTokenAddressLower); - console2.log("Pool initial tick (using specified price) set to: ", _poolInitialTick); - } - - function _setPoolInitialTickFromAuctionPrice() internal { - console2.log("Auction price: ", _fpbParams.price); - _poolInitialTick = - _getTickFromPrice(_fpbParams.price, _baseTokenDecimals, _isBaseTokenAddressLower); - console2.log("Pool initial tick (using auction price) set to: ", _poolInitialTick); - } - - modifier givenPoolInitialTick( - int24 poolInitialTick_ - ) { - _setPoolInitialTickFromTick(poolInitialTick_); - _; - } - - function _setFloorRangeGap( - int24 tickSpacingWidth_ - ) internal { - _floorRangeGap = tickSpacingWidth_; - console2.log("Floor range gap set to: ", _floorRangeGap); - _createData.floorRangeGap = _floorRangeGap; - } - - modifier givenFloorRangeGap( - int24 tickSpacingWidth_ - ) { - _setFloorRangeGap(tickSpacingWidth_); - _; - } - - function _createBPOOL() internal { - // Generate a salt so that the base token address is higher (or lower) than the quote token - console2.log("Generating salt for BPOOL"); - bytes32 baseTokenSalt = ComputeAddress.generateSalt( - _BASELINE_QUOTE_TOKEN, - !_isBaseTokenAddressLower, - type(BPOOLv1).creationCode, - abi.encode( - _baselineKernel, - "Base Token", - "BT", - _baseTokenDecimals, - address(_uniV3Factory), - _BASELINE_QUOTE_TOKEN, - _feeTier, - _poolInitialTick, - address(_blast), - _blastGovernor - ), - address(this) - ); - - // Create a new BPOOL with the given fee tier - console2.log("Creating BPOOL"); - _baseToken = new BPOOLv1{salt: baseTokenSalt}( - _baselineKernel, - "Base Token", - "BT", - _baseTokenDecimals, - address(_uniV3Factory), - _BASELINE_QUOTE_TOKEN, - _feeTier, - _poolInitialTick, - address(_blast), - _blastGovernor - ); - - // Assert that the token ordering is correct - if (_isBaseTokenAddressLower) { - require(address(_baseToken) < _BASELINE_QUOTE_TOKEN, "Base token > quote token"); - } else { - require(address(_baseToken) > _BASELINE_QUOTE_TOKEN, "Base token < quote token"); - } - - // Install the BPOOL module - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.InstallModule, address(_baseToken)); - - // Install the CREDT module - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.InstallModule, address(_creditModule)); - - // Install the LOOPS module - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.InstallModule, address(_loopsModule)); - - // Activate MarketMaking - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, address(_marketMaking)); - - // Activate the BPOOL minter - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, address(_bPoolMinter)); - } - - modifier givenBPoolIsCreated() { - _createBPOOL(); - _; - } - - function _createCallback() internal { - if (address(_baseToken) == address(0)) { - revert("Base token not created"); - } - - // Get the salt - bytes memory args = - abi.encode(address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - bytes32 salt = - _getTestSalt("BaselineAxisLaunch", type(BaselineAxisLaunch).creationCode, args); - - // Required for CREATE2 address to work correctly. doesn't do anything in a test - // Source: https://github.com/foundry-rs/foundry/issues/6402 - vm.startBroadcast(); - _dtl = new BaselineAxisLaunch{salt: salt}( - address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER - ); - vm.stopBroadcast(); - - _dtlAddress = address(_dtl); - - // Install as a policy - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, _dtlAddress); - } - - modifier givenCallbackIsCreated() virtual { - _createCallback(); - _; - } - - modifier givenAuctionFormatIsEmp() { - _auctionModule = _empModule; - _mockGetAuctionModuleForId(); - _; - } - - function _createAuction() internal { - console2.log(""); - console2.log("Creating auction in FPB module"); - - // Create a dummy auction in the module - IAuction.AuctionParams memory auctionParams = IAuction.AuctionParams({ - start: _START, - duration: 1 days, - capacityInQuote: false, - capacity: _scaleBaseTokenAmount(_LOT_CAPACITY), - implParams: abi.encode(_fpbParams) - }); - - vm.prank(address(_auctionHouse)); - _fpbModule.auction(_lotId, auctionParams, _quoteTokenDecimals, _baseTokenDecimals); - } - - modifier givenAuctionIsCreated() { - _createAuction(); - _; - } - - function _onCreate( - address seller_ - ) internal { - console2.log(""); - console2.log("Calling onCreate callback"); - vm.prank(address(_auctionHouse)); - _dtl.onCreate( - _lotId, - seller_, - address(_baseToken), - address(_quoteToken), - _scaleBaseTokenAmount(_LOT_CAPACITY), - true, - abi.encode(_createData) - ); - } - - function _onCreate() internal { - _onCreate(_SELLER); - } - - modifier givenOnCreate() { - _onCreate(); - _; - } - - function _onCancel() internal { - console2.log(""); - console2.log("Calling onCancel callback"); - vm.prank(address(_auctionHouse)); - _dtl.onCancel(_lotId, _scaleBaseTokenAmount(_LOT_CAPACITY), true, abi.encode("")); - } - - modifier givenOnCancel() { - _onCancel(); - _; - } - - function _onSettle( - bytes memory err_ - ) internal { - console2.log(""); - console2.log("Calling onSettle callback"); - - uint256 capacityRefund = _scaleBaseTokenAmount(_refund); - console2.log("capacity refund", capacityRefund); - uint256 curatorFeeRefund = capacityRefund * _curatorFee / _LOT_CAPACITY; - console2.log("curator fee refund", curatorFeeRefund); - - if (err_.length > 0) { - vm.expectRevert(err_); - } - - vm.prank(address(_auctionHouse)); - _dtl.onSettle( - _lotId, - _proceeds - _protocolFee - _referrerFee, - capacityRefund + curatorFeeRefund, - abi.encode("") - ); - } - - function _onSettle() internal { - _onSettle(""); - } - - modifier givenOnSettle() { - _onSettle(); - _; - } - - function _onCurate( - uint256 curatorFee_ - ) internal { - console2.log(""); - console2.log("Calling onCurate callback"); - vm.prank(address(_auctionHouse)); - _dtl.onCurate(_lotId, curatorFee_, true, abi.encode("")); - } - - modifier givenOnCurate( - uint256 curatorFee_ - ) { - _onCurate(curatorFee_); - _; - } - - modifier givenBPoolFeeTier( - uint24 feeTier_ - ) { - _feeTier = feeTier_; - _tickSpacing = _uniV3Factory.feeAmountTickSpacing(_feeTier); - _; - } - - modifier givenBaseTokenAddressHigher() { - _isBaseTokenAddressLower = false; - - _setPoolInitialTickFromAuctionPrice(); - _; - } - - modifier givenBaseTokenDecimals( - uint8 decimals_ - ) { - _baseTokenDecimals = decimals_; - - _setPoolInitialTickFromAuctionPrice(); - _; - } - - modifier givenFixedPrice( - uint256 fixedPrice_ - ) { - _fpbParams.price = fixedPrice_; - console2.log("Fixed price set to: ", fixedPrice_); - - _setPoolInitialTickFromAuctionPrice(); - _; - } - - modifier givenAnchorUpperTick( - int24 anchorTickU_ - ) { - _createData.anchorTickU = anchorTickU_; - console2.log("Anchor tick U set to: ", anchorTickU_); - _; - } - - function _setAnchorTickWidth( - int24 anchorTickWidth_ - ) internal { - _createData.anchorTickWidth = anchorTickWidth_; - } - - modifier givenAnchorTickWidth( - int24 anchorTickWidth_ - ) { - _setAnchorTickWidth(anchorTickWidth_); - _; - } - - function _scaleBaseTokenAmount( - uint256 amount_ - ) internal view returns (uint256) { - return FixedPointMathLib.mulDivDown(amount_, 10 ** _baseTokenDecimals, _BASE_SCALE); - } - - modifier givenAddressHasBaseTokenBalance(address account_, uint256 amount_) { - _mintBaseTokens(account_, amount_); - _; - } - - modifier givenAddressHasQuoteTokenBalance(address account_, uint256 amount_) { - console2.log("Minting quote tokens to: ", account_); - _quoteToken.mint(account_, amount_); - _; - } - - function _disableTransferLock() internal { - vm.prank(_OWNER); - _bPoolMinter.setTransferLock(false); - } - - function _enableTransferLock() internal { - vm.prank(_OWNER); - _bPoolMinter.setTransferLock(true); - } - - function _transferBaseToken(address to_, uint256 amount_) internal { - // Unlock transfers - // This mimics the manual call that the seller needs to do before cancelling/settling - _disableTransferLock(); - - // Transfer refund from auction house to the callback - // We transfer instead of minting to not affect the supply - vm.prank(address(_auctionHouse)); - _baseToken.transfer(to_, amount_); - - // Lock transfers - _enableTransferLock(); - } - - function _transferBaseTokenRefund( - uint256 amount_ - ) internal { - console2.log("Transferring base token refund to DTL: ", amount_); - - _transferBaseToken(_dtlAddress, amount_); - } - - modifier givenBaseTokenRefundIsTransferred( - uint256 amount_ - ) { - _transferBaseTokenRefund(amount_); - _; - } - - function _getTickFromPrice( - uint256 price_, - uint8 baseTokenDecimals_, - bool isBaseTokenAddressLower_ - ) internal pure returns (int24 tick) { - // Get sqrtPriceX96 - uint160 sqrtPriceX96 = SqrtPriceMath.getSqrtPriceX96( - _BASELINE_QUOTE_TOKEN, - isBaseTokenAddressLower_ - ? address(0x0000000000000000000000000000000000000001) - : address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), - price_, - 10 ** baseTokenDecimals_ - ); - - // Convert to tick - return TickMath.getTickAtSqrtRatio(sqrtPriceX96); - } - - function _getRangeReserves( - Range range_ - ) internal view returns (uint256) { - Position memory position = _baseToken.getPosition(range_); - - return position.reserves; - } - - function _getRangeBAssets( - Range range_ - ) internal view returns (uint256) { - Position memory position = _baseToken.getPosition(range_); - - return position.bAssets; - } - - function _mintBaseTokens(address account_, uint256 amount_) internal { - vm.prank(_OWNER); - _bPoolMinter.mint(account_, amount_); - } - - function _setPoolPercent( - uint24 poolPercent_ - ) internal { - _createData.poolPercent = poolPercent_; - } - - modifier givenPoolPercent( - uint24 poolPercent_ - ) { - _setPoolPercent(poolPercent_); - _; - } - - function _setFloorReservesPercent( - uint24 floorReservesPercent_ - ) internal { - _createData.floorReservesPercent = floorReservesPercent_; - } - - modifier givenFloorReservesPercent( - uint24 floorReservesPercent_ - ) { - _setFloorReservesPercent(floorReservesPercent_); - _; - } - - function _roundToTickSpacingUp( - int24 activeTick_ - ) internal view returns (int24) { - // Rounds down - int24 roundedTick = (activeTick_ / _tickSpacing) * _tickSpacing; - - // Add a tick spacing to round up - // This mimics BPOOL.getActiveTS() - if (activeTick_ >= 0 || activeTick_ % _tickSpacing == 0) { - roundedTick += _tickSpacing; - } - - return roundedTick; - } - - function _mockLotFees() internal { - // Mock on the AuctionHouse - vm.mockCall( - address(_auctionHouse), - abi.encodeWithSelector(IAuctionHouse.lotFees.selector, _lotId), - abi.encode( - address(0), true, _curatorFeePercent, _protocolFeePercent, _referrerFeePercent - ) - ); - } - - function _setCuratorFeePercent( - uint48 curatorFeePercent_ - ) internal { - _curatorFeePercent = curatorFeePercent_; - - // Update mock - _mockLotFees(); - - // Update the value - _curatorFee = _LOT_CAPACITY * _curatorFeePercent / 100e2; - } - - modifier givenCuratorFeePercent( - uint48 curatorFeePercent_ - ) { - _setCuratorFeePercent(curatorFeePercent_); - _; - } - - function _setProtocolFeePercent( - uint48 protocolFeePercent_ - ) internal { - _protocolFeePercent = protocolFeePercent_; - - // Update mock - _mockLotFees(); - - // Update the value - _protocolFee = _proceeds * _protocolFeePercent / 100e2; - } - - modifier givenProtocolFeePercent( - uint48 protocolFeePercent_ - ) { - _setProtocolFeePercent(protocolFeePercent_); - _; - } - - function _setReferrerFeePercent( - uint48 referrerFeePercent_ - ) internal { - _referrerFeePercent = referrerFeePercent_; - - // Update mock - _mockLotFees(); - - // Update the value - _referrerFee = _proceeds * _referrerFeePercent / 100e2; - } - - modifier givenReferrerFeePercent( - uint48 referrerFeePercent_ - ) { - _setReferrerFeePercent(referrerFeePercent_); - _; - } - - function _setTotalCollateralized(address user_, uint256 totalCollateralized_) internal { - // Mint enough base tokens to cover the total collateralized - _mintBaseTokens(user_, totalCollateralized_); - - // Approve the spending of the base tokens - vm.prank(user_); - _baseToken.approve(address(_bPoolMinter), totalCollateralized_); - - _disableTransferLock(); - - // Borrow - vm.prank(user_); - _bPoolMinter.allocateCreditAccount(user_, totalCollateralized_, 365); - - _enableTransferLock(); - } - - modifier givenCollateralized(address user_, uint256 totalCollateralized_) { - _setTotalCollateralized(user_, totalCollateralized_); - _; - } - - function _setPoolTargetTick( - int24 poolTargetTick_ - ) internal { - _createData.poolTargetTick = poolTargetTick_; - console2.log("Pool target tick set to: ", poolTargetTick_); - } - - modifier givenPoolTargetTick( - int24 poolTargetTick_ - ) { - _setPoolTargetTick(poolTargetTick_); - _; - } - - // ========== MOCKS ========== // - - function _mockGetAuctionModuleForId() internal { - vm.mockCall( - address(_auctionHouse), - abi.encodeWithSelector(IAuctionHouse.getAuctionModuleForId.selector, _lotId), - abi.encode(address(_auctionModule)) - ); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol deleted file mode 100644 index c2192e1e..00000000 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/BaselineCappedAllowlistTest.sol +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Test scaffolding -import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; - -// Axis -import {BALwithCappedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; - -// Baseline -import {Actions as BaselineKernelActions} from "@baseline/Kernel.sol"; - -contract BaselineCappedAllowlistTest is BaselineAxisLaunchTest { - uint256 internal constant _BUYER_LIMIT = 5e18; - - // ========== MODIFIERS ========== // - - modifier givenCallbackIsCreated() override { - // Get the salt - bytes memory args = - abi.encode(address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - bytes32 salt = - _getTestSalt("BaselineCappedAllowlist", type(BALwithCappedAllowlist).creationCode, args); - - // Required for CREATE2 address to work correctly. doesn't do anything in a test - // Source: https://github.com/foundry-rs/foundry/issues/6402 - vm.startBroadcast(); - _dtl = new BALwithCappedAllowlist{salt: salt}( - address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER - ); - vm.stopBroadcast(); - - _dtlAddress = address(_dtl); - - // Install as a policy - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, _dtlAddress); - _; - } - - modifier givenAllowlistParams(bytes32 merkleRoot_, uint256 buyerLimit_) { - _createData.allowlistParams = abi.encode(merkleRoot_, buyerLimit_); - _; - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol deleted file mode 100644 index ee282419..00000000 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onBid.t.sol +++ /dev/null @@ -1,211 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BALwithCappedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; - -contract BaselineCappedAllowlistOnBidTest is BaselineCappedAllowlistTest { - // Use the @openzeppelin/merkle-tree package or the scripts in axis-utils to generate the merkle tree - - // Values: - // 0x0000000000000000000000000000000000000004 - // 0x0000000000000000000000000000000000000005 - bytes32 internal constant _MERKLE_ROOT = - 0xc92348ba87c65979cc4f264810321a35efa64e795075908af2c507a22d4da472; - bytes32 internal constant _BUYER_MERKLE_PROOF = - 0x16db2e4b9f8dc120de98f8491964203ba76de27b27b29c2d25f85a325cd37477; - bytes32 internal constant _NOT_SELLER_MERKLE_PROOF = - 0xc167b0e3c82238f4f2d1a50a8b3a44f96311d77b148c30dc0ef863e1a060dcb6; - - bytes32[] internal _proof; - - uint64 internal constant _BID_ID = 1; - - // ========== MODIFIER ========== // - - modifier givenMerkleProof( - bytes32 merkleProof_ - ) { - bytes32[] memory proof = new bytes32[](1); - proof[0] = merkleProof_; - - _proof = proof; - _; - } - - function _onBid( - uint256 bidAmount_ - ) internal { - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, bidAmount_, abi.encode(_proof)); - } - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the merkle proof is invalid - // [X] it reverts - // [X] when the buyer is not in the merkle tree - // [X] it reverts - // [X] when the buyer has already spent their limit - // [X] it reverts - // [X] when the buyer has not made a bid - // [X] when the bid amount is over the buyer's limit - // [X] it reverts - // [X] it updates the spent amount with the bid amount - // [X] when the bid amount is over the remaining limit - // [X] it reverts - // [X] it updates the spent amount with the bid amount - - function test_parametersInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - { - // Expect revert - vm.expectRevert(); - - // Call the callback with an invalid parameter format - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, 5e18, abi.encode(uint256(20), bytes("something"))); - } - - function test_merkleProofInvalid_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_NOT_SELLER_MERKLE_PROOF) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback with an invalid merkle proof - _onBid(5e18); - } - - function test_buyerNotInMerkleTree_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, address(0x55), 5e18, abi.encode(_proof)); - } - - function test_buyerLimitSpent_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Spend the allocation - _onBid(5e18); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithCappedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback again - _onBid(1e18); - } - - function test_noBids_aboveLimit_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithCappedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback - _onBid(6e18); - } - - function test_noBids_belowLimit() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Call the callback - _onBid(4e18); - - // Check the buyer spent amount - assertEq(BALwithCappedAllowlist(address(_dtl)).buyerSpent(_BUYER), 4e18, "buyer spent"); - } - - function test_remainingLimit_aboveLimit_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Spend the allocation - _onBid(4e18); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BALwithCappedAllowlist.Callback_ExceedsLimit.selector); - vm.expectRevert(err); - - // Call the callback again - _onBid(2e18); - } - - function test_remainingLimit_belowLimit() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenMerkleProof(_BUYER_MERKLE_PROOF) - { - // Spend the allocation - _onBid(4e18); - - // Call the callback - _onBid(1e18); - - // Check the buyer spent amount - assertEq(BALwithCappedAllowlist(address(_dtl)).buyerSpent(_BUYER), 5e18, "buyer spent"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol deleted file mode 100644 index ecfa8901..00000000 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/onCreate.t.sol +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BALwithCappedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; - -contract BaselineCappedAllowlistOnCreateTest is BaselineCappedAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the buyer limit is 0 - // [X] it reverts - // [X] when the seller is not the owner - // [X] it reverts - // [X] it decodes and stores the merkle root - - function test_allowlistParamsIncorrect_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Set the allowlist parameters to be an incorrect format - _createData.allowlistParams = abi.encode(uint256(20), bytes32("hello"), uint256(10)); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_buyerLimitZero_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, uint256(0)) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_sellerNotOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(_OWNER); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - { - // Call the callback - _onCreate(); - - // Check the merkle root is stored - assertEq(BALwithCappedAllowlist(address(_dtl)).merkleRoot(), _MERKLE_ROOT, "merkle root"); - - // Check the buyer limit is stored - assertEq(BALwithCappedAllowlist(address(_dtl)).buyerLimit(), _BUYER_LIMIT, "buyer limit"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol b/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol deleted file mode 100644 index c2689855..00000000 --- a/test/callbacks/liquidity/BaselineV2/CappedAllowlist/setMerkleRoot.t.sol +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineCappedAllowlistTest} from "./BaselineCappedAllowlistTest.sol"; - -import {BALwithCappedAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithCappedAllowlist.sol"; -import {BALwithAllowlist} from - "../../../../../src/callbacks/liquidity/BaselineV2/BALwithAllowlist.sol"; - -contract BaselineCappedAllowlistSetMerkleRootTest is BaselineCappedAllowlistTest { - /// @dev This doesn't need to be valid at the moment - bytes32 internal constant _MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - bytes32 internal constant _NEW_MERKLE_ROOT = - 0x1234567890123456789012345678901234567890123456789012345678901234; - - function _setMerkleRoot() internal { - vm.prank(_SELLER); - BALwithCappedAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - // ========== TESTS ========== // - - // [X] when the caller is not the owner - // [X] it reverts - // [X] when the auction has not been registered - // [X] it reverts - // [X] when the auction has been completed - // [X] it reverts - // [X] the merkle root is updated and an event is emitted - - function test_notOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - { - // Expect revert - vm.expectRevert("UNAUTHORIZED"); - - // Call the callback - BALwithCappedAllowlist(address(_dtl)).setMerkleRoot(_NEW_MERKLE_ROOT); - } - - function test_auctionNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BALwithAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_auctionCompleted_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform onSettle callback - _onSettle(); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BALwithAllowlist.Callback_InvalidState.selector); - vm.expectRevert(err); - - // Call the callback - _setMerkleRoot(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_MERKLE_ROOT, _BUYER_LIMIT) - givenOnCreate - { - // Call the callback - _setMerkleRoot(); - - // Check the merkle root is updated - assertEq( - BALwithCappedAllowlist(address(_dtl)).merkleRoot(), _NEW_MERKLE_ROOT, "merkle root" - ); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/MockBlast.sol b/test/callbacks/liquidity/BaselineV2/MockBlast.sol deleted file mode 100644 index e3352b25..00000000 --- a/test/callbacks/liquidity/BaselineV2/MockBlast.sol +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {YieldMode, GasMode} from "@baseline/utils/IBlast.sol"; - -/// @dev Implements the minimum interface required for BlastClaimer to interact with this contract. -contract MockBlast { - function configure(YieldMode _yield, GasMode gasMode, address governor) external { - // Do nothing - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol deleted file mode 100644 index 8b34b12c..00000000 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/BaselineTokenAllowlistTest.sol +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -// Test scaffolding -import {BaselineAxisLaunchTest} from "../BaselineAxisLaunchTest.sol"; -import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; - -// Axis -import { - BALwithTokenAllowlist, - ITokenBalance -} from "../../../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; - -// Baseline -import {Actions as BaselineKernelActions} from "@baseline/Kernel.sol"; - -contract BaselineTokenAllowlistTest is BaselineAxisLaunchTest { - uint96 internal constant _TOKEN_THRESHOLD = 5e18; - MockERC20 internal _token; - - // ========== MODIFIERS ========== // - - modifier givenCallbackIsCreated() override { - // Get the salt - bytes memory args = - abi.encode(address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER); - bytes32 salt = - _getTestSalt("BaselineTokenAllowlist", type(BALwithTokenAllowlist).creationCode, args); - - // Required for CREATE2 address to work correctly. doesn't do anything in a test - // Source: https://github.com/foundry-rs/foundry/issues/6402 - vm.startBroadcast(); - _dtl = new BALwithTokenAllowlist{salt: salt}( - address(_auctionHouse), _BASELINE_KERNEL, _BASELINE_QUOTE_TOKEN, _SELLER - ); - vm.stopBroadcast(); - - _dtlAddress = address(_dtl); - - // Install as a policy - vm.prank(_OWNER); - _baselineKernel.executeAction(BaselineKernelActions.ActivatePolicy, _dtlAddress); - _; - } - - modifier givenAllowlistParams(address tokenBalance_, uint96 tokenThreshold_) { - _createData.allowlistParams = abi.encode(ITokenBalance(tokenBalance_), tokenThreshold_); - _; - } - - modifier givenTokenIsCreated() { - _token = new MockERC20("Token", "TKN", 18); - _; - } - - modifier givenAccountHasTokenBalance(address account, uint256 balance) { - _token.mint(account, balance); - _; - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol deleted file mode 100644 index 09df0d09..00000000 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onBid.t.sol +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineTokenAllowlistTest} from "./BaselineTokenAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; - -contract BaselineTokenAllowlistOnBidTest is BaselineTokenAllowlistTest { - uint64 internal constant _BID_ID = 1; - - // ========== MODIFIER ========== // - - function _onBid( - uint256 bidAmount_ - ) internal { - // Call the callback - vm.prank(address(_auctionHouse)); - _dtl.onBid(_lotId, _BID_ID, _BUYER, bidAmount_, abi.encode("")); - } - - // ========== TESTS ========== // - - // [X] if the buyer has below the threshold - // [X] it reverts - // [X] it succeeds - - function test_buyerBelowThreshold_reverts( - uint256 bidAmount_, - uint256 tokenBalance_ - ) - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - givenAllowlistParams(address(_token), _TOKEN_THRESHOLD) - givenOnCreate - { - uint256 bidAmount = bound(bidAmount_, 1, 10e18); - uint256 tokenBalance = bound(tokenBalance_, 0, _TOKEN_THRESHOLD - 1); - - // Mint the token balance - _token.mint(_BUYER, tokenBalance); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onBid(bidAmount); - } - - function test_success( - uint256 bidAmount_, - uint256 tokenBalance_ - ) - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - givenAllowlistParams(address(_token), _TOKEN_THRESHOLD) - givenOnCreate - { - uint256 bidAmount = bound(bidAmount_, 1, 10e18); - uint256 tokenBalance = bound(tokenBalance_, _TOKEN_THRESHOLD, _TOKEN_THRESHOLD * 2); - - // Mint the token balance - _token.mint(_BUYER, tokenBalance); - - // Call the callback - _onBid(bidAmount); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol deleted file mode 100644 index 01cfc377..00000000 --- a/test/callbacks/liquidity/BaselineV2/TokenAllowlist/onCreate.t.sol +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineTokenAllowlistTest} from "./BaselineTokenAllowlistTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import { - BALwithTokenAllowlist, - ITokenBalance -} from "../../../../../src/callbacks/liquidity/BaselineV2/BALwithTokenAllowlist.sol"; - -contract BaselineTokenAllowlistOnCreateTest is BaselineTokenAllowlistTest { - // ========== TESTS ========== // - - // [X] when the allowlist parameters are in an incorrect format - // [X] it reverts - // [X] when the seller is not the owner - // [X] it reverts - // [X] if the token is not a contract - // [X] it reverts - // [X] if the token balance is not retrievable - // [X] it reverts - // [X] it sets the token address and buyer limit - - function test_allowlistParamsIncorrect_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - { - // Set the allowlist parameters to be an incorrect format - _createData.allowlistParams = abi.encode(uint256(20), bytes32("hello"), uint256(10)); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_sellerNotOwner_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - givenAllowlistParams(address(_token), _TOKEN_THRESHOLD) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(_OWNER); - } - - function test_tokenNotContract_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAllowlistParams(_SELLER, _TOKEN_THRESHOLD) // Set the token to be an address that is not a contract - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_tokenBalanceNotRetrievable_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - givenAllowlistParams(address(_auctionHouse), _TOKEN_THRESHOLD) // Set the token to be a contract that does not have a balanceOf function - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Call the callback - _onCreate(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenTokenIsCreated - givenAuctionIsCreated - givenAllowlistParams(address(_token), _TOKEN_THRESHOLD) - { - // Call the callback - _onCreate(); - - // Check the token address and buyer limit are stored - (ITokenBalance token, uint256 threshold) = BALwithTokenAllowlist(address(_dtl)).tokenCheck(); - - assertEq(address(token), address(_token), "token address"); - assertEq(threshold, _TOKEN_THRESHOLD, "token threshold"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/onCancel.t.sol b/test/callbacks/liquidity/BaselineV2/onCancel.t.sol deleted file mode 100644 index d04f2bb4..00000000 --- a/test/callbacks/liquidity/BaselineV2/onCancel.t.sol +++ /dev/null @@ -1,142 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BaselineAxisLaunch} from - "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; - -contract BaselineOnCancelTest is BaselineAxisLaunchTest { - // ============ Modifiers ============ // - - // ============ Assertions ============ // - - // ============ Tests ============ // - - // [X] when the lot has not been registered - // [X] it reverts - // [X] when the caller is not the auction house - // [X] it reverts - // [X] when the lot has already been cancelled - // [X] it reverts - // [X] when the lot has already been settled - // [X] it reverts - // [X] when an insufficient quantity of the base token is transferred to the callback - // [X] it reverts - // [X] it updates circulating supply, marks the auction as completed and burns the refunded base token quantity - - function test_lotNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCancel(); - } - - function test_notAuctionHouse_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Perform callback - _dtl.onCancel(_lotId, _LOT_CAPACITY, true, abi.encode("")); - } - - function test_lotAlreadyCancelled_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - givenOnCancel - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback - _onCancel(); - } - - function test_lotAlreadySettled_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform onSettle callback - _onSettle(); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback - _onCancel(); - } - - function test_insufficientRefund_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaselineAxisLaunch.Callback_MissingFunds.selector); - vm.expectRevert(err); - - // Perform callback - _onCancel(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - { - // Transfer capacity from auction house back to the callback - // We transfer instead of minting to not affect the supply - _transferBaseToken(_dtlAddress, _LOT_CAPACITY); - - // Perform callback - _onCancel(); - - // Check the circulating supply is updated - assertEq(_baseToken.totalSupply(), 0, "circulating supply"); - - // Check the auction is marked as completed - assertEq(_dtl.auctionComplete(), true, "auction completed"); - - // Check the refunded base token quantity is burned - assertEq(_baseToken.balanceOf(_dtlAddress), 0, "base token: callback balance"); - assertEq(_baseToken.balanceOf(address(_baseToken)), 0, "base token: contract balance"); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/onCreate.t.sol b/test/callbacks/liquidity/BaselineV2/onCreate.t.sol deleted file mode 100644 index 7a137ccc..00000000 --- a/test/callbacks/liquidity/BaselineV2/onCreate.t.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; - -/* -// Test scaffolding -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; -import {BaselineAxisLaunch} from "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -*/ - -contract BaselineAxisLaunchOnCreateTest { -// Tests temporarily disabled -} diff --git a/test/callbacks/liquidity/BaselineV2/onCurate.t.sol b/test/callbacks/liquidity/BaselineV2/onCurate.t.sol deleted file mode 100644 index 2e72b018..00000000 --- a/test/callbacks/liquidity/BaselineV2/onCurate.t.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; - -contract BaselineOnCurateTest is BaselineAxisLaunchTest { - // ============ Modifiers ============ // - - // ============ Assertions ============ // - - // ============ Tests ============ // - - // [X] when the lot has not been registered - // [X] it reverts - // [X] when the caller is not the auction house - // [X] it reverts - // [X] when the curator fee is zero - // [X] it does nothing - // [X] it mints the base token to the auction house - - function test_lotNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onCurate(0); - } - - function test_notAuctionHouse_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Perform callback - _dtl.onCurate(_lotId, 0, true, abi.encode("")); - } - - function test_curatorFeeNonZero( - uint256 curatorFee_ - ) public givenBPoolIsCreated givenCallbackIsCreated givenAuctionIsCreated givenOnCreate { - uint256 curatorFee = bound(curatorFee_, 1, type(uint96).max); - uint256 balanceBefore = _baseToken.balanceOf(address(_auctionHouse)); - - // Perform callback - _onCurate(curatorFee); - - // Assert that the base token was minted to the auction house - assertEq( - _baseToken.balanceOf(address(_auctionHouse)), - balanceBefore + curatorFee, - "base token: auction house" - ); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_curatorFeeZero() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - { - uint256 balanceBefore = _baseToken.balanceOf(address(_auctionHouse)); - - // Perform callback - _onCurate(0); - - // Assert that the base token was minted to the auction house - assertEq( - _baseToken.balanceOf(address(_auctionHouse)), balanceBefore, "base token: auction house" - ); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/onSettle.t.sol b/test/callbacks/liquidity/BaselineV2/onSettle.t.sol deleted file mode 100644 index 39175820..00000000 --- a/test/callbacks/liquidity/BaselineV2/onSettle.t.sol +++ /dev/null @@ -1,1098 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BaselineAxisLaunch} from - "../../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {Range} from "@baseline/modules/BPOOL.v1.sol"; -import {FixedPointMathLib} from "@solmate-6.8.0/utils/FixedPointMathLib.sol"; -import {IUniswapV3Pool} from - "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Pool.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; - -import {console2} from "@forge-std-1.9.1/console2.sol"; - -contract BaselineOnSettleTest is BaselineAxisLaunchTest { - using FixedPointMathLib for uint256; - - uint256 internal _additionalQuoteTokensMinted; - - // ============ Modifiers ============ // - - modifier givenFullCapacity() { - _proceeds = 30e18; - _refund = 0; - _; - } - - // ============ Assertions ============ // - - function _assertQuoteTokenBalances() internal view { - assertEq(_quoteToken.balanceOf(_dtlAddress), 0, "quote token: callback"); - assertEq(_quoteToken.balanceOf(address(_quoteToken)), 0, "quote token: contract"); - - uint256 proceedsAfterFees = _proceeds - _protocolFee - _referrerFee; - uint256 poolProceeds = proceedsAfterFees * _createData.poolPercent / 100e2; - assertEq( - _quoteToken.balanceOf(address(_baseToken.pool())), - poolProceeds + _additionalQuoteTokensMinted, - "quote token: pool" - ); - assertEq( - _quoteToken.balanceOf(_SELLER), proceedsAfterFees - poolProceeds, "quote token: seller" - ); - } - - function _assertBaseTokenBalances( - uint256 curatorFee_ - ) internal view { - assertEq(_baseToken.balanceOf(_dtlAddress), 0, "base token: callback"); - assertEq(_baseToken.balanceOf(address(_baseToken)), 0, "base token: contract"); - - uint256 totalSupply = _baseToken.totalSupply(); - console2.log("totalSupply", totalSupply); - - // No payout distributed to "bidders", so don't account for it here - uint256 spotSupply = _LOT_CAPACITY - _refund; - console2.log("spotSupply", spotSupply); - - uint256 poolSupply = - totalSupply - spotSupply - curatorFee_ - _creditModule.totalCollateralized(); - assertEq(_baseToken.balanceOf(address(_baseToken.pool())), poolSupply, "base token: pool"); - assertEq(_baseToken.balanceOf(_SELLER), 0, "base token: seller"); - } - - function _assertCirculatingSupply( - uint256 curatorFee_ - ) internal view { - uint256 totalSupply = _baseToken.totalSupply(); - - assertApproxEqAbs( - totalSupply - _baseToken.getPosition(Range.FLOOR).bAssets - - _baseToken.getPosition(Range.ANCHOR).bAssets - - _baseToken.getPosition(Range.DISCOVERY).bAssets, - _LOT_CAPACITY - _refund + curatorFee_ + _creditModule.totalCollateralized(), - 2, // There is a difference (rounding error?) of 2 - "circulating supply" - ); - } - - function _assertAuctionComplete() internal view { - assertEq(_dtl.auctionComplete(), true, "auction completed"); - } - - function _assertPoolReserves() internal view { - uint256 poolProceeds = - (_proceeds - _protocolFee - _referrerFee) * _createData.poolPercent / 100e2; - uint256 floorProceeds = poolProceeds * _createData.floorReservesPercent / 100e2; - assertApproxEqAbs( - _getRangeReserves(Range.FLOOR), - floorProceeds, - 1, // There is a difference (rounding error?) of 1 - "reserves: floor" - ); - assertApproxEqAbs( - _getRangeReserves(Range.ANCHOR), - poolProceeds - floorProceeds, - 1, // There is a difference (rounding error?) of 1 - "reserves: anchor" - ); - assertEq(_getRangeReserves(Range.DISCOVERY), 0, "reserves: discovery"); - - // BAssets deployed into the pool - assertEq(_getRangeBAssets(Range.FLOOR), 0, "bAssets: floor"); - assertGt(_getRangeBAssets(Range.ANCHOR), 0, "bAssets: anchor"); // As the pool tick is below the anchor upper tick, there will always be bAssets in the anchor range - assertGt(_getRangeBAssets(Range.DISCOVERY), 0, "bAssets: discovery"); - } - - // ============ Tests ============ // - - // [X] when the lot has not been registered - // [X] it reverts - // [X] when the caller is not the auction house - // [X] it reverts - // [X] given the onSettle callback has already been called - // [X] when onSettle is called - // [X] it reverts - // [X] when onCancel is called - // [X] it reverts - // [X] when onCurate is called - // [X] it reverts - // [X] when onCreate is called - // [X] it reverts - // [X] when the lot has already been cancelled - // [X] it reverts - // [X] when insufficient proceeds are sent to the callback - // [X] it reverts - // [X] when insufficient refund is sent to the callback - // [X] it reverts - // [X] given there is liquidity in the pool at a higher tick - // [X] it adjusts the pool price - // [X] given there is liquidity in the pool at a lower tick - // [X] it adjusts the pool price - // [X] when the percent in floor reserves changes - // [X] it adds reserves to the floor and anchor ranges in the correct proportions - // [X] given a curator fee has been paid - // [X] the solvency check passes - // [X] given there are credit account allocations - // [X] it includes the allocations in the solvency check - // [ ] given there is loop vault debt - // [ ] it includes the debt in the solvency check - // [X] given the allocation of proceeds to the pool is not 100% - // [X] it allocates the proceeds correctly - // [X] given the anchor range width is fuzzed - // [X] it allocates the proceeds correctly - // [X] given the active tick is fuzzed - // [X] it allocates the proceeds correctly - // [X] given the protocol fee is set - // [X] it correctly performs the solvency check - // [X] given the referrer fee is set - // [X] it correctly performs the solvency check - // [X] it burns refunded base tokens, updates the circulating supply, marks the auction as completed and deploys the reserves into the Baseline pool - - // TODO handle the pool target tick - - function test_lotNotRegistered_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenAddressHasBaseTokenBalance(_dtlAddress, _REFUND_AMOUNT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Call the callback - _onSettle(); - } - - function test_notAuctionHouse_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_NotAuthorized.selector); - vm.expectRevert(err); - - // Perform callback - _dtl.onSettle( - _lotId, _PROCEEDS_AMOUNT, _scaleBaseTokenAmount(_REFUND_AMOUNT), abi.encode("") - ); - } - - function test_auctionCompleted_onCreate_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - // Expect revert - bytes memory err = abi.encodeWithSelector(BaseCallback.Callback_InvalidParams.selector); - vm.expectRevert(err); - - // Perform callback again - _onCreate(); - } - - function test_auctionCompleted_onCurate_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback again - _onCurate(0); - } - - function test_auctionCompleted_onCancel_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback again - _onCancel(); - } - - function test_auctionCompleted_onSettle_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback again - _onSettle(); - } - - function test_lotAlreadyCancelled_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - givenOnCancel - { - // Expect revert - bytes memory err = - abi.encodeWithSelector(BaselineAxisLaunch.Callback_AlreadyComplete.selector); - vm.expectRevert(err); - - // Perform callback - _onSettle(); - } - - function test_insufficientProceeds_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasBaseTokenBalance(_dtlAddress, _LOT_CAPACITY) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaselineAxisLaunch.Callback_MissingFunds.selector); - vm.expectRevert(err); - - // Perform callback - _onSettle(); - } - - function test_insufficientRefund_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - { - // Expect revert - bytes memory err = abi.encodeWithSelector(BaselineAxisLaunch.Callback_MissingFunds.selector); - vm.expectRevert(err); - - // Perform callback - _onSettle(); - } - - function test_success() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_curatorFee_low() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(30e2) // For the solvency check - givenPoolPercent(90e2) // For the solvency check - { - uint48 curatorFeePercent = 1e2; - _setCuratorFeePercent(curatorFeePercent); - - // Perform the onCreate callback - _onCreate(); - - // Perform the onCurate callback - _onCurate(_curatorFee); - - // Mint tokens - _quoteToken.mint(_dtlAddress, _PROCEEDS_AMOUNT); - _transferBaseTokenRefund(_REFUND_AMOUNT); - - uint256 refundedCuratorFee = _REFUND_AMOUNT * _curatorFee / _LOT_CAPACITY; - _transferBaseTokenRefund(refundedCuratorFee); - - // Perform the onSettle callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(_curatorFee - refundedCuratorFee); - _assertCirculatingSupply(_curatorFee - refundedCuratorFee); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_curatorFee_middle() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(60e2) // For the solvency check - givenPoolPercent(90e2) // For the solvency check - { - uint48 curatorFeePercent = 5e2; - _setCuratorFeePercent(curatorFeePercent); - - // Perform the onCreate callback - _onCreate(); - - // Perform the onCurate callback - _onCurate(_curatorFee); - - // Mint tokens - _quoteToken.mint(_dtlAddress, _PROCEEDS_AMOUNT); - _transferBaseTokenRefund(_REFUND_AMOUNT); - - uint256 refundedCuratorFee = _REFUND_AMOUNT * _curatorFee / _LOT_CAPACITY; - _transferBaseTokenRefund(refundedCuratorFee); - - // Perform the onSettle callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(_curatorFee - refundedCuratorFee); - _assertCirculatingSupply(_curatorFee - refundedCuratorFee); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_curatorFee_high() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(20e2) // For the solvency check - givenPoolPercent(99e2) // For the solvency check - { - uint48 curatorFeePercent = 10e2; - _setCuratorFeePercent(curatorFeePercent); - - // Perform the onCreate callback - _onCreate(); - - // Perform the onCurate callback - _onCurate(_curatorFee); - - // Mint tokens - _quoteToken.mint(_dtlAddress, _PROCEEDS_AMOUNT); - _transferBaseTokenRefund(_REFUND_AMOUNT); - - uint256 refundedCuratorFee = _REFUND_AMOUNT * _curatorFee / _LOT_CAPACITY; - _transferBaseTokenRefund(refundedCuratorFee); - - // Perform the onSettle callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(_curatorFee - refundedCuratorFee); - _assertCirculatingSupply(_curatorFee - refundedCuratorFee); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_givenCreditAllocations_low() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(92e2) // For the solvency check - givenCollateralized(_BORROWER, 1e18) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_givenCreditAllocations_low_givenFullCapacity() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(92e2) // For the solvency check - givenCollateralized(_BORROWER, 1e18) - givenOnCreate - givenFullCapacity - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_givenCreditAllocations_middle_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(20) // For the solvency check - givenFloorReservesPercent(25e2) // For the solvency check - givenPoolPercent(99e2) // For the solvency check - givenCollateralized(_BORROWER, 5e18) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Expect revert - // The solvency check fails due to the refund - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 979_838_626_646_539_745 - ); - - // Perform callback - _onSettle(err); - } - - function test_givenCreditAllocations_middle_givenFullCapacity() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(20) // For the solvency check - givenFloorReservesPercent(25e2) // For the solvency check - givenPoolPercent(99e2) // For the solvency check - givenCollateralized(_BORROWER, 5e18) - givenOnCreate - givenFullCapacity - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_givenCreditAllocations_high_reverts() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(31) // For the solvency check - givenCollateralized(_BORROWER, 10e18) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Expect revert - // The solvency check fails due to the refund - bytes memory err = abi.encodeWithSelector( - BaselineAxisLaunch.Callback_InvalidCapacityRatio.selector, 973_166_177_514_906_222 - ); - - // Perform callback - _onSettle(err); - } - - function test_givenCreditAllocations_high_givenFullCapacity() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(31) // For the solvency check - givenCollateralized(_BORROWER, 10e18) - givenOnCreate - givenFullCapacity - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_floorReservesPercent_lowPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(91e2) // For the solvency check - givenFloorReservesPercent(10e2) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_floorReservesPercent_highPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(83e2) // For the solvency check - givenFloorReservesPercent(90e2) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_floorReservesPercent_middlePercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenFloorReservesPercent(50e2) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_poolPercent_lowPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(10e2) - givenFloorRangeGap(137) // For the solvency check - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_poolPercent_middlePercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(50e2) - givenFloorRangeGap(44) // For the solvency check - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_poolPercent_highPercent() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(90e2) - givenFloorReservesPercent(10e2) // For the solvency check - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_anchorTickWidth_low() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(10) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_anchorTickWidth_middle() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(30) - givenPoolPercent(63e2) // For the solvency check - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_anchorTickWidth_high() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenAnchorTickWidth(50) - givenFloorReservesPercent(10e2) // For the solvency check - givenPoolPercent(58e2) // For the solvency check - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function uniswapV3MintCallback(uint256, uint256 amount1Owed, bytes calldata) external { - console2.log("Minting additional quote tokens", amount1Owed); - _additionalQuoteTokensMinted += amount1Owed; - - // Transfer the quote tokens - _quoteToken.mint(msg.sender, amount1Owed); - } - - function _mintPosition(int24 tickLower_, int24 tickUpper_) internal { - // Using PoC: https://github.com/GuardianAudits/axis-1/pull/4/files - IUniswapV3Pool pool = _baseToken.pool(); - - pool.mint(address(this), tickLower_, tickUpper_, 1e18, ""); - } - - function uniswapV3SwapCallback(int256, int256, bytes memory) external pure { - return; - } - - function _swap( - uint160 sqrtPrice_ - ) internal { - IUniswapV3Pool pool = _baseToken.pool(); - - pool.swap(address(this), true, 1, sqrtPrice_, ""); - } - - function test_existingReservesAtHigherPoolTick() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap at a tick higher than the anchor range - IUniswapV3Pool pool = _baseToken.pool(); - pool.swap(address(this), false, 1, TickMath.getSqrtRatioAtTick(60_000), ""); - - // Assert that the pool tick has moved higher - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 60_000, "pool tick after swap"); - - // Provide reserve tokens to the pool at a tick higher than the anchor range and lower than the new active tick - _mintPosition(12_000, 12_000 + _tickSpacing); - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, _POOL_TARGET_TICK, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - // _assertCirculatingSupply(0); // Difficult to calculate the additional base tokens minted - _assertAuctionComplete(); - // _assertPoolReserves(); // Difficult to calculate the additional quote and base tokens into ranges - } - - function test_existingReservesAtHigherPoolTick_noLiquidity() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap at a tick higher than the anchor range - IUniswapV3Pool pool = _baseToken.pool(); - pool.swap(address(this), false, 1, TickMath.getSqrtRatioAtTick(60_000), ""); - - // Assert that the pool tick has moved higher - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 60_000, "pool tick after swap"); - - // Do not mint any liquidity above the anchor range - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, _POOL_TARGET_TICK, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_existingReservesAtHigherPoolTick_givenPoolTargetTick() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolTargetTick(10_900) // Different to _POOL_TARGET_TICK - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap at a tick higher than the anchor range - IUniswapV3Pool pool = _baseToken.pool(); - pool.swap(address(this), false, 1, TickMath.getSqrtRatioAtTick(60_000), ""); - - // Assert that the pool tick has moved higher - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 60_000, "pool tick after swap"); - - // Provide reserve tokens to the pool at a tick higher than the anchor range and lower than the new active tick - _mintPosition(12_000, 12_000 + _tickSpacing); - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_900, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - // _assertCirculatingSupply(0); // Difficult to calculate the additional base tokens minted - _assertAuctionComplete(); - // _assertPoolReserves(); // Difficult to calculate the additional quote and base tokens into ranges - } - - function test_existingReservesAtLowerPoolTick() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Provide reserve tokens to the pool at a lower tick - _mintPosition(-60_000 - _tickSpacing, -60_000); - - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap - _swap(TickMath.getSqrtRatioAtTick(-60_000)); - - // Assert that the pool price has moved lower - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, -60_001, "pool tick after swap"); - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, _POOL_TARGET_TICK, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_existingReservesAtLowerPoolTick_noLiquidity() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Don't mint any liquidity - - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap - _swap(TickMath.getSqrtRatioAtTick(-60_000)); - - // Assert that the pool price has moved lower - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, -60_000, "pool tick after swap"); - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, _POOL_TARGET_TICK, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_existingReservesAtLowerPoolTick_givenPoolTargetTick() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolTargetTick(10_900) // Different to _POOL_TARGET_TICK - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Provide reserve tokens to the pool at a lower tick - _mintPosition(-60_000 - _tickSpacing, -60_000); - - // Assert the pool price - int24 poolTick; - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_986, "pool tick after mint"); // Original active tick - - // Swap - _swap(TickMath.getSqrtRatioAtTick(-60_000)); - - // Assert that the pool price has moved lower - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, -60_001, "pool tick after swap"); - - // Perform callback - _onSettle(); - - // Assert that the pool tick has corrected - (, poolTick,,,,,) = _baseToken.pool().slot0(); - assertEq(poolTick, 10_900, "pool tick after settlement"); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - } - - function test_givenProtocolFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(1e2) // 1% - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds - _protocolFee) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_givenReferrerFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenReferrerFeePercent(1e2) // 1% - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds - _referrerFee) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } - - function test_givenProtocolFee_givenReferrerFee() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenProtocolFeePercent(5e1) // 0.5% - givenReferrerFeePercent(5e1) // 0.5% - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _proceeds - _protocolFee - _referrerFee) - givenBaseTokenRefundIsTransferred(_refund) - { - // Perform callback - _onSettle(); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(0); - _assertCirculatingSupply(0); - _assertAuctionComplete(); - _assertPoolReserves(); - - // Transfer lock should be enabled - assertEq(_baseToken.locked(), true, "transfer lock"); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/slide.t.sol b/test/callbacks/liquidity/BaselineV2/slide.t.sol deleted file mode 100644 index b8e90bd4..00000000 --- a/test/callbacks/liquidity/BaselineV2/slide.t.sol +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {Range} from "@baseline/modules/BPOOL.v1.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; - -import {console2} from "@forge-std-1.9.1/console2.sol"; - -contract BaselineOnSettleSlideTest is BaselineAxisLaunchTest { - function uniswapV3SwapCallback( - int256 amount0Delta_, - int256 amount1Delta_, - bytes memory - ) external { - console2.log("amount0Delta", amount0Delta_); - console2.log("amount1Delta", amount1Delta_); - - if (amount0Delta_ > 0) { - _baseToken.transfer(msg.sender, uint256(amount0Delta_)); - } - - if (amount1Delta_ > 0) { - _quoteToken.transfer(msg.sender, uint256(amount1Delta_)); - } - - return; - } - - function test_floorReservesPercent_lowPercent_slide() - public - givenFixedPrice(1e18) - givenAnchorUpperTick(200) - givenPoolTargetTick(199) // Below anchor upper tick - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(92e2) // For the solvency check - givenFloorReservesPercent(10e2) - givenAnchorTickWidth(10) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, 8e18) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - _proceeds = 8e18; - _refund = _REFUND_AMOUNT; - - // Perform callback - _onSettle(); - - // Report the range ticks - (int24 floorL, int24 floorU) = _baseToken.getTicks(Range.FLOOR); - (int24 anchorL, int24 anchorU) = _baseToken.getTicks(Range.ANCHOR); - (int24 discoveryL, int24 discoveryU) = _baseToken.getTicks(Range.DISCOVERY); - console2.log("floor lower", floorL); - console2.log("floor upper", floorU); - console2.log("anchor lower", anchorL); - console2.log("anchor upper", anchorU); - console2.log("discovery lower", discoveryL); - console2.log("discovery upper", discoveryU); - - // Check the tick - (, int24 poolTick,,,,,) = _baseToken.pool().slot0(); - console2.log("pool tick after settlement", poolTick); - - // Transfer base tokens from AuctionHouse to here (so we don't mess with solvency) - _transferBaseToken(address(this), 8e18); - - // This only works if: - // - there are circulating base tokens - // - the transfer lock is disabled - - // Swap base tokens to reduce the pool price - _disableTransferLock(); - _baseToken.pool().swap(_SELLER, true, 8e18, TickMath.MIN_SQRT_RATIO + 1, ""); - _enableTransferLock(); - - // Check the tick - (, poolTick,,,,,) = _baseToken.pool().slot0(); - console2.log("pool tick after swap", poolTick); - - // Attempt to slide - _disableTransferLock(); - _marketMaking.slide(); - _enableTransferLock(); - - // Check the tick - (, poolTick,,,,,) = _baseToken.pool().slot0(); - console2.log("pool tick after slide", poolTick); - - // Report the range ticks - (floorL, floorU) = _baseToken.getTicks(Range.FLOOR); - (anchorL, anchorU) = _baseToken.getTicks(Range.ANCHOR); - (discoveryL, discoveryU) = _baseToken.getTicks(Range.DISCOVERY); - console2.log("floor lower", floorL); - console2.log("floor upper", floorU); - console2.log("anchor lower", anchorL); - console2.log("anchor upper", anchorU); - console2.log("discovery lower", discoveryL); - console2.log("discovery upper", discoveryU); - } -} -*/ diff --git a/test/callbacks/liquidity/BaselineV2/sweep.t.sol b/test/callbacks/liquidity/BaselineV2/sweep.t.sol deleted file mode 100644 index eba88789..00000000 --- a/test/callbacks/liquidity/BaselineV2/sweep.t.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {BaselineAxisLaunchTest} from "./BaselineAxisLaunchTest.sol"; - -import {Range} from "@baseline/modules/BPOOL.v1.sol"; -import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; - -import {console2} from "@forge-std-1.9.1/console2.sol"; - -contract BaselineOnSettleSlideTest is BaselineAxisLaunchTest { - function uniswapV3SwapCallback( - int256 amount0Delta_, - int256 amount1Delta_, - bytes memory - ) external { - console2.log("amount0Delta", amount0Delta_); - console2.log("amount1Delta", amount1Delta_); - - if (amount0Delta_ > 0) { - _baseToken.transfer(msg.sender, uint256(amount0Delta_)); - } - - if (amount1Delta_ > 0) { - _quoteToken.transfer(msg.sender, uint256(amount1Delta_)); - } - - return; - } - - function test_floorReservesPercent_highPercent_sweep() - public - givenBPoolIsCreated - givenCallbackIsCreated - givenAuctionIsCreated - givenPoolPercent(83e2) // For the solvency check - givenFloorReservesPercent(90e2) - givenAnchorTickWidth(10) - givenOnCreate - givenAddressHasQuoteTokenBalance(_dtlAddress, _PROCEEDS_AMOUNT) - givenBaseTokenRefundIsTransferred(_REFUND_AMOUNT) - { - // Perform callback - _onSettle(); - - // Report the range ticks - (int24 floorL, int24 floorU) = _baseToken.getTicks(Range.FLOOR); - (int24 anchorL, int24 anchorU) = _baseToken.getTicks(Range.ANCHOR); - (int24 discoveryL, int24 discoveryU) = _baseToken.getTicks(Range.DISCOVERY); - console2.log("floor lower", floorL); - console2.log("floor upper", floorU); - console2.log("anchor lower", anchorL); - console2.log("anchor upper", anchorU); - console2.log("discovery lower", discoveryL); - console2.log("discovery upper", discoveryU); - - // Check the tick - (, int24 poolTick,,,,,) = _baseToken.pool().slot0(); - console2.log("pool tick after settlement", poolTick); - - // Mint quote tokens for the swap - _quoteToken.mint(address(this), 150e18); - - // Swap quote tokens to reduce the pool price - _disableTransferLock(); - _baseToken.pool().swap(_SELLER, false, 150e18, TickMath.MAX_SQRT_RATIO - 1, ""); - _enableTransferLock(); - - // Check the tick - (, poolTick,,,,,) = _baseToken.pool().slot0(); - console2.log("pool tick after swap", poolTick); - - // Attempt to sweep - assertEq(_marketMaking.canSweep(), true, "canSweep"); - - // Do the sweep - _disableTransferLock(); - _marketMaking.sweep(); - _enableTransferLock(); - - // Report the range ticks - (floorL, floorU) = _baseToken.getTicks(Range.FLOOR); - (anchorL, anchorU) = _baseToken.getTicks(Range.ANCHOR); - (discoveryL, discoveryU) = _baseToken.getTicks(Range.DISCOVERY); - console2.log("floor lower", floorL); - console2.log("floor upper", floorU); - console2.log("anchor lower", anchorL); - console2.log("anchor upper", anchorU); - console2.log("discovery lower", discoveryL); - console2.log("discovery upper", discoveryU); - } -} -*/ diff --git a/test/invariant/AxisInvariant.sol b/test/invariant/AxisInvariant.sol index 49e64ca9..afcb334b 100644 --- a/test/invariant/AxisInvariant.sol +++ b/test/invariant/AxisInvariant.sol @@ -3,10 +3,8 @@ pragma solidity ^0.8.0; import {UniswapV2DTLHandler} from "./handlers/UniswapV2DTLHandler.sol"; import {UniswapV3DTLHandler} from "./handlers/UniswapV3DTLHandler.sol"; -// import {BaselineDTLHandler} from "./handlers/BaselineDTLHandler.sol"; import {V2PoolHandler} from "./handlers/V2PoolHandler.sol"; import {V3PoolHandler} from "./handlers/V3PoolHandler.sol"; -// import {BaselinePoolHandler} from "./handlers/BaselinePoolHandler.sol"; // forgefmt: disable-start /**************************************************************************************************************/ @@ -14,13 +12,6 @@ import {V3PoolHandler} from "./handlers/V3PoolHandler.sol"; /*** the Axis Fuzz Suite. ***/ /**************************************************************************************************************/ // forgefmt: disable-end -// contract AxisInvariant is -// UniswapV2DTLHandler, -// UniswapV3DTLHandler, -// BaselineDTLHandler, -// V2PoolHandler, -// V3PoolHandler, -// BaselinePoolHandler contract AxisInvariant is UniswapV2DTLHandler, UniswapV3DTLHandler, V2PoolHandler, V3PoolHandler { constructor() payable { setup(); diff --git a/test/invariant/Setup.sol b/test/invariant/Setup.sol index ed294275..9b0089ae 100644 --- a/test/invariant/Setup.sol +++ b/test/invariant/Setup.sol @@ -6,7 +6,6 @@ import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; import {IAuction} from "@axis-core-1.0.4/interfaces/modules/IAuction.sol"; -import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; import {BatchAuctionHouse} from "@axis-core-1.0.4/BatchAuctionHouse.sol"; import {EncryptedMarginalPrice} from "@axis-core-1.0.4/modules/auctions/batch/EMP.sol"; import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; @@ -26,43 +25,25 @@ import {IUniswapV3Factory} from import {UniswapV3Factory} from "../lib/uniswap-v3/UniswapV3Factory.sol"; import {WETH9} from "./modules/WETH.sol"; import {SwapRouter} from "./modules/uniswapv3-periphery/SwapRouter.sol"; -import {FixedPointMathLib} from "@solmate-6.8.0/utils/FixedPointMathLib.sol"; import {SqrtPriceMath} from "../../src/lib/uniswap-v3/SqrtPriceMath.sol"; import {TickMath} from "@uniswap-v3-core-1.0.1-solc-0.8-simulate/libraries/TickMath.sol"; -import {BaseDirectToLiquidity} from "../../src/callbacks/liquidity/BaseDTL.sol"; import {UniswapV2DirectToLiquidity} from "../../src/callbacks/liquidity/UniswapV2DTL.sol"; import {UniswapV3DirectToLiquidity} from "../../src/callbacks/liquidity/UniswapV3DTL.sol"; import {LinearVesting} from "@axis-core-1.0.4/modules/derivatives/LinearVesting.sol"; import {MockBatchAuctionModule} from "@axis-core-1.0.4-test/modules/Auction/MockBatchAuctionModule.sol"; -import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.sol"; - -// import {BaselineAxisLaunch} from "../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; - -// Baseline -// import {Kernel, Actions, Module, toKeycode as toBaselineKeycode} from "@baseline/Kernel.sol"; - import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -// import {BPOOLv1, Range, Position} from "@baseline/modules/BPOOL.v1.sol"; -// import {BPOOLMinter} from "./modules/BPOOLMinter.sol"; -// import {CREDTMinter} from "./modules/CREDTMinter.sol"; -// import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; -// import {LOOPSv1} from "@baseline/modules/LOOPS.v1.sol"; -import {ModuleTester, ModuleTestFixture} from "./modules/ModuleTester.sol"; import {WithSalts} from "../../script/salts/WithSalts.s.sol"; import {TestConstants} from "../Constants.sol"; -import {console2} from "@forge-std-1.9.1/console2.sol"; -import {MockBatchAuctionHouse} from "./mocks/MockBatchAuctionHouse.sol"; import {MockBlast} from "./mocks/MockBlast.sol"; abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { using Callbacks for UniswapV2DirectToLiquidity; using Callbacks for UniswapV3DirectToLiquidity; - // using Callbacks for BaselineAxisLaunch; /*////////////////////////////////////////////////////////////////////////// GLOBAL VARIABLES @@ -104,11 +85,9 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { uint96 internal _lotId = 1; string internal constant UNISWAP_PREFIX = "E6"; - string internal constant BASELINE_PREFIX = "EF"; address internal _dtlV2Address; address internal _dtlV3Address; - address internal _dtlBaselineAddress; IFixedPriceBatch.AuctionDataParams internal _fpbParams = IFixedPriceBatch.AuctionDataParams({price: _FIXED_PRICE, minFillPercent: 100e2}); @@ -118,7 +97,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { //////////////////////////////////////////////////////////////////////////*/ BatchAuctionHouse internal _auctionHouse; - MockBatchAuctionHouse internal _baselineAuctionHouse; UniswapV2DirectToLiquidity internal _dtlV2; @@ -132,11 +110,8 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { WETH9 internal _weth; SwapRouter internal _v3SwapRouter; - // BaselineAxisLaunch internal _dtlBaseline; - EncryptedMarginalPrice internal _empModule; FixedPriceBatch internal _fpbModule; - // Kernel internal _kernel; LinearVesting internal _linearVesting; MockBatchAuctionModule internal _batchAuctionModule; @@ -146,12 +121,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { MockERC20 internal _quoteToken; MockERC20 internal _baseToken; - // BPOOLv1 internal _baselineToken; - // CREDTv1 internal _credt; - // LOOPSv1 internal _loops; - - // BPOOLMinter internal _bpoolMinter; - // CREDTMinter internal _credtMinter; /*////////////////////////////////////////////////////////////////////////// EVENTS @@ -173,7 +142,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { // Create an BatchAuctionHouse at a deterministic address, since it is used as input to callbacks _auctionHouse = new BatchAuctionHouse(_OWNER, _PROTOCOL, _permit2Address); - _baselineAuctionHouse = new MockBatchAuctionHouse(_OWNER, _PROTOCOL, _permit2Address); _uniV2Factory = new UniswapV2FactoryClone(); @@ -181,10 +149,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { _linearVesting = new LinearVesting(address(_auctionHouse)); _batchAuctionModule = new MockBatchAuctionModule(address(_auctionHouse)); - _empModule = new EncryptedMarginalPrice(address(_baselineAuctionHouse)); - _fpbModule = new FixedPriceBatch(address(_baselineAuctionHouse)); - - _auctionModule = _fpbModule; // Install a mock batch auction module vm.prank(_OWNER); @@ -258,70 +222,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { _blast = new MockBlast(); _updatePoolInitialTick(); - - // _kernel = new Kernel(); - - // _baselineToken = _deployBPOOL( - // _kernel, - // "Base Token", - // "BT", - // _baseTokenDecimals, - // address(_uniV3Factory), - // address(_quoteToken), - // _feeTier, - // _poolInitialTick, - // address(_blast), - // address(0) - // ); - - // _credt = new CREDTv1(_kernel, address(_blast), address(0)); - - // _loops = new LOOPSv1(_kernel, 1); - - // _bpoolMinter = new BPOOLMinter(_kernel); - // _credtMinter = new CREDTMinter(_kernel); - - // _kernel.executeAction(Actions.InstallModule, address(_baselineToken)); - // _kernel.executeAction(Actions.ActivatePolicy, address(_bpoolMinter)); - - // _kernel.executeAction(Actions.InstallModule, address(_credt)); - // _kernel.executeAction(Actions.ActivatePolicy, address(_credtMinter)); - - // _kernel.executeAction(Actions.InstallModule, address(_loops)); - - // vm.prank(_OWNER); - // _baselineAuctionHouse.installModule(_fpbModule); - // vm.prank(_OWNER); - // _baselineAuctionHouse.installModule(_empModule); - - // bytes memory baselineSaltArgs = abi.encodePacked( - // type(BaselineAxisLaunch).creationCode, - // abi.encode( - // address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER - // ) - // ); - - // string[] memory baselineInputs = new string[](7); - // baselineInputs[0] = "./test/invariant/helpers/salt_hash.sh"; - // baselineInputs[1] = "--bytecodeHash"; - // baselineInputs[2] = toHexString(keccak256(baselineSaltArgs)); - // baselineInputs[3] = "--prefix"; - // baselineInputs[4] = BASELINE_PREFIX; - // baselineInputs[5] = "--deployer"; - // baselineInputs[6] = toString(address(this)); - - // bytes memory baselineRes = vm.ffi(baselineInputs); - // bytes32 baselineSalt = abi.decode(baselineRes, (bytes32)); - - // _dtlBaseline = new BaselineAxisLaunch{salt: baselineSalt}( - // address(_baselineAuctionHouse), address(_kernel), address(_quoteToken), _SELLER - // ); - - // _dtlBaselineAddress = address(_dtlBaseline); - - // _bpoolMinter.setTransferLock(false); - - // _kernel.executeAction(Actions.ActivatePolicy, _dtlBaselineAddress); } function randomAddress( @@ -493,31 +393,6 @@ abstract contract Setup is Test, Permit2User, WithSalts, TestConstants { _baseToken.mint(address_, amount_); } - // function givenAddressHasBaselineTokenBalance(address account_, uint256 amount_) internal { - // _baselineToken.mint(account_, amount_); - // } - - // function _disableTransferLock() internal { - // _bpoolMinter.setTransferLock(false); - // } - - // function _enableTransferLock() internal { - // _bpoolMinter.setTransferLock(true); - // } - - // function _transferBaselineTokenRefund( - // uint256 amount_ - // ) internal { - // _disableTransferLock(); - - // // Transfer refund from auction house to the callback - // // We transfer instead of minting to not affect the supply - // vm.prank(address(_baselineAuctionHouse)); - // _baselineToken.transfer(_dtlBaselineAddress, amount_); - - // _enableTransferLock(); - // } - function givenAddressHasBaseTokenAllowance( address owner_, address spender_, diff --git a/test/invariant/handlers/BaselineDTLHandler.sol b/test/invariant/handlers/BaselineDTLHandler.sol deleted file mode 100644 index 1d22323a..00000000 --- a/test/invariant/handlers/BaselineDTLHandler.sol +++ /dev/null @@ -1,461 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.0; -/* -import {BeforeAfter} from "../helpers/BeforeAfter.sol"; -import {Assertions} from "../helpers/Assertions.sol"; - -import {Callbacks} from "@axis-core-1.0.4/lib/Callbacks.sol"; -import {Permit2User} from "@axis-core-1.0.4-test/lib/permit2/Permit2User.sol"; - -import {IAuction} from "@axis-core-1.0.4/interfaces/modules/IAuction.sol"; -import {IAuctionHouse} from "@axis-core-1.0.4/interfaces/IAuctionHouse.sol"; -import {BatchAuctionHouse} from "@axis-core-1.0.4/BatchAuctionHouse.sol"; -import {ILinearVesting} from "@axis-core-1.0.4/interfaces/modules/derivatives/ILinearVesting.sol"; -import {IFixedPriceBatch} from "@axis-core-1.0.4/interfaces/modules/auctions/IFixedPriceBatch.sol"; - -import {GUniFactory} from "@g-uni-v1-core-0.9.9/GUniFactory.sol"; -import {GUniPool} from "@g-uni-v1-core-0.9.9/GUniPool.sol"; -import {IUniswapV3Pool} from - "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Pool.sol"; -import {IUniswapV3Factory} from - "@uniswap-v3-core-1.0.1-solc-0.8-simulate/interfaces/IUniswapV3Factory.sol"; -import {SqrtPriceMath} from "../../../src/lib/uniswap-v3/SqrtPriceMath.sol"; - -import {BaseCallback} from "@axis-core-1.0.4/bases/BaseCallback.sol"; -import {BaselineAxisLaunch} from - "../../../src/callbacks/liquidity/BaselineV2/BaselineAxisLaunch.sol"; -import {BaseDirectToLiquidity} from "../../../src/callbacks/liquidity/BaseDTL.sol"; -import {UniswapV3DirectToLiquidity} from "../../../src/callbacks/liquidity/UniswapV3DTL.sol"; -import {LinearVesting} from "@axis-core-1.0.4/modules/derivatives/LinearVesting.sol"; -import {MockBatchAuctionModule} from - "@axis-core-1.0.4-test/modules/Auction/MockBatchAuctionModule.sol"; - -import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.sol"; -import {Veecode} from "@axis-core-1.0.4/modules/Modules.sol"; - -import {BPOOLv1, Range, Position} from "@baseline/modules/BPOOL.v1.sol"; - -import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; -import {FixedPointMathLib} from "@solmate-6.8.0/utils/FixedPointMathLib.sol"; - -abstract contract BaselineDTLHandler is BeforeAfter, Assertions { - ////////////////////////////////////////////////////////////////////////// - // HANDLER VARIABLES - ////////////////////////////////////////////////////////////////////////// - - uint256 internal lotCapacity; - - uint256 internal baselineCuratorFee_; - - BaselineAxisLaunch.CreateData internal _createData; - - address internal sellerBaseline_; - - int24 internal _ANCHOR_TICK_WIDTH; - int24 internal _DISCOVERY_TICK_WIDTH; - uint24 internal _FLOOR_RESERVES_PERCENT; - int24 internal _FLOOR_RANGE_GAP; - int24 internal _ANCHOR_TICK_U; - uint24 internal _POOL_PERCENT; - - ////////////////////////////////////////////////////////////////////////// - // TARGET FUNCTIONS - ////////////////////////////////////////////////////////////////////////// - - function baselineDTL_createLot() public { - // PRE-CONDITIONS - if (_dtlBaseline.lotId() != type(uint96).max) return; - sellerBaseline_ = _SELLER; - - lotCapacity = 10 ether; - - _ANCHOR_TICK_WIDTH = int24(int256(bound(uint256(int256(_ANCHOR_TICK_WIDTH)), 10, 50))); - _DISCOVERY_TICK_WIDTH = int24(int256(bound(uint256(int256(_DISCOVERY_TICK_WIDTH)), 1, 500))); - _FLOOR_RESERVES_PERCENT = uint24(bound(uint256(_FLOOR_RESERVES_PERCENT), 10e2, 90e2)); - _FLOOR_RANGE_GAP = int24(int256(bound(uint256(int256(_FLOOR_RANGE_GAP)), 0, 500))); - _ANCHOR_TICK_U = _baselineToken.getActiveTS(); - _POOL_PERCENT = 100e2; - - _createData = BaselineAxisLaunch.CreateData({ - recipient: sellerBaseline_, - poolPercent: 87e2, //_POOL_PERCENT, - floorReservesPercent: 50e2, //_FLOOR_RESERVES_PERCENT, - floorRangeGap: 0, //_FLOOR_RANGE_GAP, - anchorTickU: 11_000, //_ANCHOR_TICK_U, - anchorTickWidth: 10, //_ANCHOR_TICK_WIDTH, - poolTargetTick: 10_986, // Default tick for the auction - allowlistParams: abi.encode("") - }); - - IAuction.AuctionParams memory auctionParams = IAuction.AuctionParams({ - start: uint48(block.timestamp), - duration: 1 days, - capacityInQuote: false, - capacity: _scaleBaseTokenAmount(lotCapacity), - implParams: abi.encode(_fpbParams) - }); - - __before(_lotId, sellerBaseline_, _dtlBaselineAddress); - - // ACTION - vm.prank(address(_baselineAuctionHouse)); - try _fpbModule.auction(_lotId, auctionParams, _quoteTokenDecimals, _baseTokenDecimals) {} - catch { - assert(false); - } - - _baselineAuctionHouse.setLotCounter(_lotId + 1); - _baselineAuctionHouse.setAuctionReference(_lotId, _fpbModule.VEECODE()); - - vm.prank(address(_baselineAuctionHouse)); - try _dtlBaseline.onCreate( - _lotId, - sellerBaseline_, - address(_baselineToken), - address(_quoteToken), - _scaleBaseTokenAmount(lotCapacity), - true, - abi.encode(_createData) - ) { - // POST-CONDITIONS - __after(_lotId, sellerBaseline_, _dtlBaselineAddress); - - _assertBaselineTokenBalances(); - } catch { - assert(false); - } - } - - struct OnCancelBaselineTemps { - address sender; - uint96 lotId; - } - - function baselineDTL_onCancel(uint256 senderIndexSeed, uint256 lotIndexSeed) public { - // PRE-CONDTIONS - if (_dtlBaseline.lotId() == type(uint96).max) return; - OnCancelBaselineTemps memory d; - d.sender = randomAddress(senderIndexSeed); - - __before(_lotId, sellerBaseline_, _dtlBaselineAddress); - - vm.prank(address(_baselineAuctionHouse)); - _baselineToken.transfer(_dtlBaselineAddress, lotCapacity); - - // ACTION - vm.prank(address(_baselineAuctionHouse)); - try _dtlBaseline.onCancel(_lotId, _scaleBaseTokenAmount(lotCapacity), true, abi.encode("")) - { - // POST-CONDITIONS - __after(_lotId, sellerBaseline_, _dtlBaselineAddress); - - equal( - _after.baselineTotalSupply, - 0 + baselineCuratorFee_, - "AX-36: Baseline token total supply after _onCancel should equal 0" - ); - - equal( - _dtlBaseline.auctionComplete(), - true, - "AX-37: BaselineDTL_onCancel should mark auction completed" - ); - - equal( - _after.dtlBaselineBalance, - _before.dtlBaselineBalance, - "AX-38: When calling BaselineDTL_onCancel DTL base token balance should equal 0" - ); - - equal( - _baselineToken.balanceOf(address(_baselineToken)), - 0, - "AX-39: When calling BaselineDTL_onCancel baseline contract base token balance should equal 0" - ); - } catch (bytes memory err) { - bytes4[3] memory errors = [ - BaselineAxisLaunch.Callback_MissingFunds.selector, - BaselineAxisLaunch.Callback_AlreadyComplete.selector, - BaseCallback.Callback_InvalidParams.selector - ]; - bool expected = false; - for (uint256 i = 0; i < errors.length; i++) { - if (errors[i] == bytes4(err)) { - expected = true; - break; - } - } - assert(expected); - return; - } - } - - struct OnCurateBaselineTemps { - address sender; - uint96 lotId; - } - - function baselineDTL_onCurate( - uint256 senderIndexSeed, - uint256 lotIndexSeed, - uint256 curatorFee_ - ) public { - // PRE-CONDTIONS - if (_dtlBaseline.lotId() == type(uint96).max) return; - OnCurateBaselineTemps memory d; - d.sender = randomAddress(senderIndexSeed); - - __before(_lotId, sellerBaseline_, _dtlBaselineAddress); - - // curatorFee_ = bound(curatorFee_, 0, 5e18); - curatorFee_ = 0; - - // ACTION - vm.prank(address(_baselineAuctionHouse)); - try _dtlBaseline.onCurate(_lotId, curatorFee_, true, abi.encode("")) { - // POST-CONDITIONS - __after(_lotId, sellerBaseline_, _dtlBaselineAddress); - - equal( - _after.auctionHouseBaselineBalance, - _before.auctionHouseBaselineBalance + curatorFee_, - "AX-40: BaselineDTL_onCurate should credit auction house correct base token fees" - ); - - baselineCuratorFee_ += curatorFee_; - } catch (bytes memory err) { - bytes4[3] memory errors = [ - BaselineAxisLaunch.Callback_MissingFunds.selector, - BaselineAxisLaunch.Callback_AlreadyComplete.selector, - BaseCallback.Callback_InvalidParams.selector - ]; - bool expected = false; - for (uint256 i = 0; i < errors.length; i++) { - if (errors[i] == bytes4(err)) { - expected = true; - break; - } - } - assert(expected); - return; - } - } - - struct OnSettleBaselineTemps { - address sender; - uint96 lotId; - } - - function baselineDTL_onSettle( - uint256 senderIndexSeed, - uint256 lotIndexSeed, - uint256 proceeds_, - uint256 refund_ - ) public { - // PRE-CONDTIONS - if (_dtlBaseline.lotId() == type(uint96).max) return; - refund_ = ((lotCapacity * 4e2) / 100e2); - uint256 proceeds = lotCapacity - refund_; - - OnSettleBaselineTemps memory d; - d.sender = randomAddress(senderIndexSeed); - - __before(_lotId, sellerBaseline_, _dtlBaselineAddress); - - givenAddressHasQuoteTokenBalance(_dtlBaselineAddress, _PROCEEDS_AMOUNT); - _transferBaselineTokenRefund(_REFUND_AMOUNT); - - // ACTION - vm.prank(address(_baselineAuctionHouse)); - try _dtlBaseline.onSettle( - _lotId, _PROCEEDS_AMOUNT, _scaleBaseTokenAmount(_REFUND_AMOUNT), abi.encode("") - ) { - // POST-CONDITIONS - __after(_lotId, sellerBaseline_, _dtlBaselineAddress); - - _assertQuoteTokenBalances(); - _assertBaseTokenBalances(); - _assertCirculatingSupply(); - _assertAuctionComplete(); - _assertPoolReserves(); - } catch (bytes memory err) { - bytes4[3] memory errors = [ - BaselineAxisLaunch.Callback_MissingFunds.selector, - BaselineAxisLaunch.Callback_AlreadyComplete.selector, - BaseCallback.Callback_InvalidParams.selector - ]; - bool expected = false; - for (uint256 i = 0; i < errors.length; i++) { - if (errors[i] == bytes4(err)) { - expected = true; - break; - } - } - assert(expected); - return; - } - } - - ////////////////////////////////////////////////////////////////////////// - // HELPERS - ////////////////////////////////////////////////////////////////////////// - - function _scaleBaseTokenAmount( - uint256 amount_ - ) internal view returns (uint256) { - return FixedPointMathLib.mulDivDown(amount_, 10 ** _baseTokenDecimals, _BASE_SCALE); - } - - function _getRangeBAssets( - Range range_ - ) internal returns (uint256) { - Position memory position = _baselineToken.getPosition(range_); - - return position.bAssets; - } - - function _getRangeReserves( - Range range_ - ) internal returns (uint256) { - Position memory position = _baselineToken.getPosition(range_); - - return position.reserves; - } - - function _assertBaselineTokenBalances() internal { - equal( - _after.sellerBaselineBalance, - _before.sellerBaselineBalance, - "AX-09: DTL Callbacks should not change seller base token balance" - ); - equal( - _after.dtlBaselineBalance, - _before.dtlBaselineBalance, - "AX-10: DTL Callbacks should not change dtl base token balance" - ); - equal( - _after.auctionHouseBaselineBalance, - _scaleBaseTokenAmount(lotCapacity), - "AX-32: When calling BaselineDTL_createLot auction house base token balance should be equal to lot Capacity lotId" - ); - } - - function _assertQuoteTokenBalances() internal { - equal( - _quoteToken.balanceOf(_dtlBaselineAddress), - 0, - "AX-17: After DTL_onSettle DTL Address quote token balance should equal 0" - ); - equal( - _quoteToken.balanceOf(address(_quoteToken)), - 0, - "AX-33: After DTL_onSettle quote token balance of quote token should equal 0" - ); - uint256 poolProceeds = _PROCEEDS_AMOUNT * _createData.poolPercent / 100e2; - equal( - _quoteToken.balanceOf(address(_baselineToken.pool())), - poolProceeds, - "AX-34: BaselineDTL_onSettle should credit baseline pool with correct quote token proceeds" - ); - equal( - _after.sellerQuoteBalance, - _before.sellerQuoteBalance + _PROCEEDS_AMOUNT - poolProceeds, - "AX-35: BaselineDTL_onSettle should credit seller quote token proceeds" - ); - } - - function _assertBaseTokenBalances() internal { - equal( - _baselineToken.balanceOf(_dtlBaselineAddress), - 0, - "AX-18: After DTL_onSettle DTL Address base token balance should equal 0" - ); - equal( - _baselineToken.balanceOf(address(_baselineToken)), - 0, - "AX-41: After BaselineDTL_onSettle baseline token base token balance should equal 0" - ); - - uint256 totalSupply = _baselineToken.totalSupply(); - - // No payout distributed to "bidders", so don't account for it here - uint256 spotSupply = totalSupply - _baselineToken.getPosition(Range.FLOOR).bAssets - - _baselineToken.getPosition(Range.ANCHOR).bAssets - - _baselineToken.getPosition(Range.DISCOVERY).bAssets; - - uint256 poolSupply = totalSupply - spotSupply; - - assertApproxEq( - _baselineToken.balanceOf(address(_baselineToken.pool())), - poolSupply, - 2, - "AX-42: After BaselineDTL_onSettle baseline pool base token balance should equal baseline pool supply" - ); - equal( - _baselineToken.balanceOf(sellerBaseline_), - 0, - "AX-43: After BaselineDTL_onSettle seller baseline token balance should equal 0" - ); - } - - function _assertCirculatingSupply() internal { - uint256 totalSupply = _baselineToken.totalSupply(); - - assertApproxEq( - totalSupply - _baselineToken.getPosition(Range.FLOOR).bAssets - - _baselineToken.getPosition(Range.ANCHOR).bAssets - - _baselineToken.getPosition(Range.DISCOVERY).bAssets - _credt.totalCreditIssued(), // totalCreditIssued would affect supply, totalCollateralized will not - lotCapacity - _REFUND_AMOUNT + baselineCuratorFee_, - 2, // There is a difference (rounding error?) of 2 - "AX-44: circulating supply should equal lot capacity plus curatorFee minus refund" - ); - } - - function _assertAuctionComplete() internal { - equal( - _dtlBaseline.auctionComplete(), - true, - "AX-45: BaselineDTL_onSettle should mark auction complete" - ); - } - - function _assertPoolReserves() internal { - uint256 poolProceeds = _PROCEEDS_AMOUNT * _createData.poolPercent / 100e2; - uint256 floorProceeds = poolProceeds * _createData.floorReservesPercent / 100e2; - assertApproxEq( - _getRangeReserves(Range.FLOOR), - floorProceeds, - 1, // There is a difference (rounding error?) of 1 - "AX-46: After BaselineDTL_onSettle floor reserves should equal floor proceeds" - ); - assertApproxEq( - _getRangeReserves(Range.ANCHOR), - poolProceeds - floorProceeds, - 1, // There is a difference (rounding error?) of 1 - "AX-47: After BaselineDTL_onSettle anchor reserves should equal pool proceeds - floor proceeds" - ); - equal( - _getRangeReserves(Range.DISCOVERY), - 0, - "AX-48: After BaselineDTL_onSettle discovery reserves should equal 0" - ); - - // BAssets deployed into the pool - equal( - _getRangeBAssets(Range.FLOOR), - 0, - "AX-49: After BaselineDTL_onSettle floor bAssets should equal 0" - ); - gt( - _getRangeBAssets(Range.ANCHOR), - 0, - "AX-50: After BaselineDTL_onSettle anchor bAssets should be greater than 0" - ); - gt( - _getRangeBAssets(Range.DISCOVERY), - 0, - "AX-51: After BaselineDTL_onSettle discovery bAssets should be greater than 0" - ); - } -} -*/ diff --git a/test/invariant/handlers/BaselinePoolHandler.sol b/test/invariant/handlers/BaselinePoolHandler.sol deleted file mode 100644 index ce9b3a84..00000000 --- a/test/invariant/handlers/BaselinePoolHandler.sol +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.0; -/* -import {BeforeAfter} from "../helpers/BeforeAfter.sol"; -import {Assertions} from "../helpers/Assertions.sol"; - -import {IUniswapV3Pool} from - "../../../lib/baseline-v2/lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; -import {ISwapRouter} from "../modules/uniswapv3-periphery/interfaces/ISwapRouter.sol"; - -import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; - -abstract contract BaselinePoolHandler is BeforeAfter, Assertions { - function BaselinePoolHandler_donate(uint256 tokenIndexSeed, uint256 amount) public { - address _token = tokenIndexSeed % 2 == 0 ? address(_quoteToken) : address(_baselineToken); - - MockERC20(_token).mint(address(this), amount); - MockERC20(_token).transfer(address(_baselineToken), amount); - } - - function BaselinePoolHandler_swapToken0(uint256 recipientIndexSeed, uint256 amountIn) public { - address recipient = randomAddress(recipientIndexSeed); - if (_quoteToken.balanceOf(recipient) < 1e14) return; - amountIn = bound(amountIn, 1e14, _quoteToken.balanceOf(recipient)); - - (address token0, address token1) = address(_baselineToken) < address(_quoteToken) - ? (address(_baselineToken), address(_quoteToken)) - : (address(_quoteToken), address(_baselineToken)); - - IUniswapV3Pool pool = IUniswapV3Pool(address(_baselineToken.pool())); - if (address(pool) == address(0)) return; - - vm.prank(recipient); - _quoteToken.approve(address(_v3SwapRouter), amountIn); - - ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ - tokenIn: address(_quoteToken), - tokenOut: address(_baselineToken), - fee: 500, - recipient: recipient, - deadline: block.timestamp, - amountIn: amountIn, - amountOutMinimum: 0, - sqrtPriceLimitX96: 0 - }); - - vm.prank(recipient); - try _v3SwapRouter.exactInputSingle(params) {} catch {} - } - - function BaselinePoolHandler_swapToken1(uint256 recipientIndexSeed, uint256 amountIn) public { - address recipient = randomAddress(recipientIndexSeed); - if (_baselineToken.balanceOf(recipient) < 1e14) return; - amountIn = bound(amountIn, 1e14, _baselineToken.balanceOf(recipient)); - - (address token0, address token1) = address(_baselineToken) < address(_quoteToken) - ? (address(_baselineToken), address(_quoteToken)) - : (address(_quoteToken), address(_baselineToken)); - - IUniswapV3Pool pool = IUniswapV3Pool(address(_baselineToken.pool())); - if (address(pool) == address(0)) return; - - vm.prank(recipient); - _baselineToken.approve(address(_v3SwapRouter), amountIn); - - ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ - tokenIn: address(_baselineToken), - tokenOut: address(_quoteToken), - fee: 500, - recipient: recipient, - deadline: block.timestamp, - amountIn: amountIn, - amountOutMinimum: 0, - sqrtPriceLimitX96: 0 - }); - - vm.prank(recipient); - try _v3SwapRouter.exactInputSingle(params) {} catch {} - } -} -*/ diff --git a/test/invariant/helpers/BeforeAfter.sol b/test/invariant/helpers/BeforeAfter.sol index b0a5017c..3e03abaa 100644 --- a/test/invariant/helpers/BeforeAfter.sol +++ b/test/invariant/helpers/BeforeAfter.sol @@ -12,13 +12,9 @@ abstract contract BeforeAfter is Setup { struct Vars { address seller; uint256 sellerBaseBalance; - uint256 sellerBaselineBalance; uint256 sellerQuoteBalance; uint256 dtlBaseBalance; - uint256 dtlBaselineBalance; uint256 auctionHouseBaseBalance; - uint256 auctionHouseBaselineBalance; - uint256 baselineTotalSupply; BaseDirectToLiquidity.DTLConfiguration dtlConfigV2; BaseDirectToLiquidity.DTLConfiguration dtlConfigV3; } @@ -34,11 +30,6 @@ abstract contract BeforeAfter is Setup { _before.sellerQuoteBalance = _quoteToken.balanceOf(seller); _before.dtlBaseBalance = _baseToken.balanceOf(_dtlAddress); _before.auctionHouseBaseBalance = _baseToken.balanceOf(address(_auctionHouse)); - // _before.sellerBaselineBalance = _baselineToken.balanceOf(seller); - // _before.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); - // _before.auctionHouseBaselineBalance = - // _baselineToken.balanceOf(address(_baselineAuctionHouse)); - // _before.baselineTotalSupply = _baselineToken.totalSupply(); } function __after(uint96 lotId, address seller, address _dtlAddress) internal { @@ -49,11 +40,6 @@ abstract contract BeforeAfter is Setup { _after.sellerQuoteBalance = _quoteToken.balanceOf(seller); _after.dtlBaseBalance = _baseToken.balanceOf(_dtlAddress); _after.auctionHouseBaseBalance = _baseToken.balanceOf(address(_auctionHouse)); - // _after.sellerBaselineBalance = _baselineToken.balanceOf(seller); - // _after.dtlBaselineBalance = _baselineToken.balanceOf(_dtlAddress); - // _after.auctionHouseBaselineBalance = - // _baselineToken.balanceOf(address(_baselineAuctionHouse)); - // _after.baselineTotalSupply = _baselineToken.totalSupply(); } function _getDTLConfigurationV2( diff --git a/test/invariant/helpers/GuardianTester.sol b/test/invariant/helpers/GuardianTester.sol index 61d03eb4..ddabed81 100644 --- a/test/invariant/helpers/GuardianTester.sol +++ b/test/invariant/helpers/GuardianTester.sol @@ -5,18 +5,9 @@ import {Test} from "@forge-std-1.9.1/Test.sol"; import {console2} from "@forge-std-1.9.1/console2.sol"; import {UniswapV2DTLHandler} from "../handlers/UniswapV2DTLHandler.sol"; import {UniswapV3DTLHandler} from "../handlers/UniswapV3DTLHandler.sol"; -// import {BaselineDTLHandler} from "../handlers/BaselineDTLHandler.sol"; import {V2PoolHandler} from "../handlers/V2PoolHandler.sol"; import {V3PoolHandler} from "../handlers/V3PoolHandler.sol"; -// import {BaselinePoolHandler} from "../handlers/BaselinePoolHandler.sol"; -// contract GuardianTester is -// UniswapV2DTLHandler, -// UniswapV3DTLHandler, -// BaselineDTLHandler, -// V2PoolHandler, -// V3PoolHandler, -// BaselinePoolHandler contract GuardianTester is UniswapV2DTLHandler, UniswapV3DTLHandler, @@ -27,9 +18,7 @@ contract GuardianTester is setup(); } - function test_replay() public { - // baselineDTL_createLot(); - } + function test_replay() public {} function test_AX_52() public { V2PoolHandler_donate(1, 0); @@ -39,11 +28,6 @@ contract GuardianTester is } function test_uni_v3() public { - // baselineDTL_createLot(32834951442023372761398138891550170); - // uniswapV2DTL_createLot(0,0,0,0); - // baselineDTL_onSettle(0,0,0,0); - // uniswapV2DTL_onSettle(0,0,0,0); - // V2PoolHandler_swapToken0(24989087196341648061875939510755979066808,0); uniswapV3DTL_createLot(0, 0, 0, 0); uniswapV3DTL_onCurate(0, 0); uniswapV3DTL_onSettle(0, 813_287_864_469_051_073_156, 0, 1_005_841_494_018_651); @@ -62,12 +46,5 @@ contract GuardianTester is 12_825, 19_237_704_000 ); - // baselineDTL_createLot(); - // baselineDTL_onSettle( - // 35_823_517_419_589_735_724_585_236_993_570_690_661_427_686_147_832_812, - // 547_625_172_962_746_778_936_920_119_754_048_998_529_185_575_659_961_730_593_116, - // 413_846_032_223_724_352_952_166_507_982_050_954_163_269_860_227_480_398_133, - // 2_378_700_954_196_402_680_978_671_333_632_440_717_118_146_550_494 - // ); } } diff --git a/test/invariant/modules/BPOOLMinter.sol b/test/invariant/modules/BPOOLMinter.sol deleted file mode 100644 index 51d5ba6a..00000000 --- a/test/invariant/modules/BPOOLMinter.sol +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity 0.8.19; -/* -import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; - -import {Kernel, Keycode, toKeycode, Policy, Permissions} from "@baseline/Kernel.sol"; -import {BPOOLv1} from "@baseline/modules/BPOOL.v1.sol"; - -contract BPOOLMinter is Policy, Owned { - BPOOLv1 public BPOOL; - - constructor( - Kernel kernel_ - ) Policy(kernel_) Owned(kernel_.executor()) {} - - function configureDependencies() external override returns (Keycode[] memory dependencies) { - dependencies = new Keycode[](1); - dependencies[0] = toKeycode("BPOOL"); - - BPOOL = BPOOLv1(getModuleAddress(toKeycode("BPOOL"))); - } - - function requestPermissions() external view override returns (Permissions[] memory requests) { - requests = new Permissions[](2); - requests[0] = Permissions(toKeycode("BPOOL"), BPOOL.mint.selector); - requests[1] = Permissions(toKeycode("BPOOL"), BPOOL.setTransferLock.selector); - } - - function mint(address to_, uint256 amount_) external onlyOwner { - BPOOL.mint(to_, amount_); - } - - function setTransferLock( - bool lock_ - ) external onlyOwner { - BPOOL.setTransferLock(lock_); - } -} -*/ diff --git a/test/invariant/modules/CREDTMinter.sol b/test/invariant/modules/CREDTMinter.sol deleted file mode 100644 index 6e5bdafb..00000000 --- a/test/invariant/modules/CREDTMinter.sol +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.0; -/* -import {Owned} from "@solmate-6.8.0/auth/Owned.sol"; - -import {Kernel, Keycode, toKeycode, Policy} from "@baseline/Kernel.sol"; -import {CREDTv1} from "@baseline/modules/CREDT.v1.sol"; - -contract CREDTMinter is Policy, Owned { - CREDTv1 public CREDT; - - constructor( - Kernel kernel_ - ) Policy(kernel_) Owned(kernel_.executor()) {} - - function configureDependencies() external override returns (Keycode[] memory dependencies) { - dependencies = new Keycode[](1); - dependencies[0] = toKeycode("CREDT"); - - CREDT = CREDTv1(getModuleAddress(toKeycode("CREDT"))); - } -} -*/ diff --git a/test/invariant/modules/ModuleTester.sol b/test/invariant/modules/ModuleTester.sol deleted file mode 100644 index f5b3798d..00000000 --- a/test/invariant/modules/ModuleTester.sol +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.8.0; - -import "../../../src/callbacks/liquidity/BaselineV2/lib/Kernel.sol"; - -// Generate an UNACTIVATED test fixture policy for a module. Must be activated separately. -library ModuleTester { - // Generate a test fixture policy for a module with all permissions passed in - function generateFixture( - Module module_, - Permissions[] memory requests_ - ) internal returns (address) { - return address(new ModuleTestFixture(module_.kernel(), module_, requests_)); - } - - // Generate a test fixture policy authorized for a single module function - function generateMultiFunctionFixture( - Module module_, - bytes4[] calldata funcSelectors_ - ) internal returns (address) { - uint256 len = funcSelectors_.length; - Keycode keycode = module_.KEYCODE(); - - Permissions[] memory requests = new Permissions[](len); - for (uint256 i; i < len; ++i) { - requests[i] = Permissions(keycode, funcSelectors_[i]); - } - - return generateFixture(module_, requests); - } - - // Generate a test fixture policy authorized for a single module function - function generateFunctionFixture( - Module module_, - bytes4 funcSelector_ - ) internal returns (address) { - Permissions[] memory requests = new Permissions[](1); - requests[0] = Permissions(module_.KEYCODE(), funcSelector_); - return generateFixture(module_, requests); - } - - // Generate a test fixture policy with NO permissions - function generateDummyFixture( - Module module_ - ) internal returns (address) { - Permissions[] memory requests = new Permissions[](0); - return generateFixture(module_, requests); - } -} - -/// @notice Mock policy to allow testing gated module functions -contract ModuleTestFixture is Policy { - Module internal _module; - Permissions[] internal _requests; - - constructor(Kernel kernel_, Module module_, Permissions[] memory requests_) Policy(kernel_) { - _module = module_; - uint256 len = requests_.length; - for (uint256 i; i < len; i++) { - _requests.push(requests_[i]); - } - } - - // ========= FRAMEWORK CONFIFURATION ========= // - function configureDependencies() - external - view - override - returns (Keycode[] memory dependencies) - { - dependencies = new Keycode[](1); - dependencies[0] = _module.KEYCODE(); - } - - function requestPermissions() external view override returns (Permissions[] memory requests) { - uint256 len = _requests.length; - requests = new Permissions[](len); - for (uint256 i; i < len; i++) { - requests[i] = _requests[i]; - } - } - - function call( - bytes memory data - ) external { - (bool success,) = address(_module).call(data); - require(success, "ModuleTestFixture: call failed"); - } -} From beae888bb4f3c02e8fe5400fc7551e0514397f84 Mon Sep 17 00:00:00 2001 From: Jem <0x0xjem@gmail.com> Date: Wed, 5 Mar 2025 22:18:18 +0400 Subject: [PATCH 19/19] chore: linting --- test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol | 1 - 1 file changed, 1 deletion(-) diff --git a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol index b4d897b9..bde304ae 100644 --- a/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol +++ b/test/callbacks/liquidity/UniswapV3DTL/UniswapV3DTLTest.sol @@ -27,7 +27,6 @@ import {keycodeFromVeecode, toKeycode} from "@axis-core-1.0.4/modules/Keycode.so import {MockERC20} from "@solmate-6.8.0/test/utils/mocks/MockERC20.sol"; import {WithSalts} from "../../../../script/salts/WithSalts.s.sol"; -import {console2} from "@forge-std-1.9.1/console2.sol"; import {TestConstants} from "../../../Constants.sol"; // solhint-disable max-states-count