├── .github └── workflows │ ├── certora.yml │ └── test.yml ├── .gitignore ├── .gitmodules ├── LICENSE ├── Makefile ├── README.md ├── audit ├── 20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf ├── 20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf ├── FPS_dss-allocator_Assessment_FINAL.pdf └── cantina-report-review-makerdao-dssallocator.pdf ├── certora ├── AllocatorBuffer.conf ├── AllocatorBuffer.spec ├── AllocatorOracle.conf ├── AllocatorOracle.spec ├── AllocatorRegistry.conf ├── AllocatorRegistry.spec ├── AllocatorRoles.conf ├── AllocatorRoles.spec ├── AllocatorVault.conf ├── AllocatorVault.spec └── funnels │ ├── Auxiliar.sol │ ├── DepositorUniV3.conf │ ├── DepositorUniV3.spec │ ├── Swapper.conf │ ├── Swapper.spec │ └── automation │ ├── ConduitMover.conf │ ├── ConduitMover.spec │ ├── StableDepositorUniV3.conf │ ├── StableDepositorUniV3.spec │ ├── StableSwapper.conf │ ├── StableSwapper.spec │ ├── VaultMinter.conf │ └── VaultMinter.spec ├── deploy ├── AllocatorDeploy.sol ├── AllocatorInit.sol ├── AllocatorInstances.sol └── funnels │ ├── AllocatorFunnelDeploy.sol │ ├── AllocatorFunnelInit.sol │ └── AllocatorFunnelInstance.sol ├── foundry.toml ├── script └── funnels │ └── automation │ ├── run_conduit_mover.sh │ ├── run_stable_depositor.sh │ └── run_stable_swapper.sh ├── src ├── AllocatorBuffer.sol ├── AllocatorOracle.sol ├── AllocatorRegistry.sol ├── AllocatorRoles.sol ├── AllocatorVault.sol ├── IAllocatorConduit.sol └── funnels │ ├── DepositorUniV3.sol │ ├── Swapper.sol │ ├── automation │ ├── ConduitMover.sol │ ├── StableDepositorUniV3.sol │ ├── StableSwapper.sol │ └── VaultMinter.sol │ ├── callees │ ├── SwapperCalleePsm.sol │ └── SwapperCalleeUniV3.sol │ └── uniV3 │ ├── FullMath.sol │ ├── LiquidityAmounts.sol │ └── TickMath.sol └── test ├── AllocatorBuffer.t.sol ├── AllocatorOracle.t.sol ├── AllocatorRegistry.t.sol ├── AllocatorRoles.t.sol ├── AllocatorVault.t.sol ├── funnels ├── DepositorUniV3.t.sol ├── Swapper.t.sol ├── UniV3Utils.sol ├── automation │ ├── ConduitMover.t.sol │ ├── StableDepositorUniV3.t.sol │ ├── StableSwapper.t.sol │ └── VaultMinter.t.sol └── callees │ ├── SwapperCalleePsm.t.sol │ └── SwapperCalleeUniV3.t.sol ├── integration └── Deployment.t.sol └── mocks ├── AllocatorConduitMock.sol ├── AuthedMock.sol ├── CalleeMock.sol ├── Gem0Mock.sol ├── Gem1Mock.sol ├── GemMock.sol ├── JugMock.sol ├── PoolUniV3Mock.sol ├── PsmMock.sol ├── RolesMock.sol ├── UsdsJoinMock.sol ├── UsdsMock.sol └── VatMock.sol /.github/workflows/certora.yml: -------------------------------------------------------------------------------- 1 | name: Certora 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | certora: 7 | name: Certora 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | allocator: 13 | - buffer 14 | - vault 15 | - roles 16 | - oracle 17 | - registry 18 | - swapper 19 | - depositoruniv3 20 | - stable-swapper 21 | - stable-depositoruniv3 22 | - conduit-mover 23 | 24 | steps: 25 | - name: Checkout 26 | uses: actions/checkout@v3 27 | 28 | - uses: actions/setup-java@v3 29 | with: 30 | distribution: 'zulu' 31 | java-version: '11' 32 | java-package: jre 33 | 34 | - name: Set up Python 3.8 35 | uses: actions/setup-python@v4 36 | with: 37 | python-version: 3.8 38 | 39 | - name: Install solc-select 40 | run: pip3 install solc-select 41 | 42 | - name: Solc Select 0.8.16 43 | run: solc-select install 0.8.16 44 | 45 | - name: Install Certora 46 | run: pip3 install certora-cli-beta 47 | 48 | - name: Certora verify ${{ matrix.allocator }} 49 | run: make certora-${{ matrix.allocator }} 50 | env: 51 | CERTORAKEY: ${{ secrets.CERTORAKEY }} 52 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | tests: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | 11 | - name: Install Foundry 12 | uses: foundry-rs/foundry-toolchain@v1 13 | with: 14 | version: nightly 15 | 16 | - name: Install Dependencies 17 | run: forge install 18 | 19 | - name: Run tests 20 | run: forge test 21 | env: 22 | ETH_RPC_URL: ${{ secrets.ETH_RPC_URL }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiler files 2 | cache/ 3 | out/ 4 | 5 | # Ignores development broadcast logs 6 | !/broadcast 7 | /broadcast/*/31337/ 8 | /broadcast/**/dry-run/ 9 | 10 | # Docs 11 | docs/ 12 | 13 | # Dotenv file 14 | .env 15 | tmp 16 | 17 | # Certora 18 | .*certora* 19 | .last_confs/ 20 | *.zip 21 | resource_errors.json 22 | .zip-output-url.txt 23 | certora_debug_log.txt 24 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/dss-test"] 2 | path = lib/dss-test 3 | url = https://github.com/makerdao/dss-test 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PATH := ~/.solc-select/artifacts/solc-0.8.16:~/.solc-select/artifacts:$(PATH) 2 | certora-buffer :; PATH=${PATH} certoraRun certora/AllocatorBuffer.conf$(if $(rule), --rule $(rule),) 3 | certora-vault :; PATH=${PATH} certoraRun certora/AllocatorVault.conf$(if $(rule), --rule $(rule),) 4 | certora-roles :; PATH=${PATH} certoraRun certora/AllocatorRoles.conf$(if $(rule), --rule $(rule),) 5 | certora-oracle :; PATH=${PATH} certoraRun certora/AllocatorOracle.conf$(if $(rule), --rule $(rule),) 6 | certora-registry :; PATH=${PATH} certoraRun certora/AllocatorRegistry.conf$(if $(rule), --rule $(rule),) 7 | certora-swapper :; PATH=${PATH} certoraRun certora/funnels/Swapper.conf$(if $(rule), --rule $(rule),) 8 | certora-depositoruniv3 :; PATH=${PATH} certoraRun certora/funnels/DepositorUniV3.conf$(if $(rule), --rule $(rule),) 9 | certora-vault-minter :; PATH=${PATH} certoraRun certora/funnels/automation/VaultMinter.conf$(if $(rule), --rule $(rule),) 10 | certora-stable-swapper :; PATH=${PATH} certoraRun certora/funnels/automation/StableSwapper.conf$(if $(rule), --rule $(rule),) 11 | certora-stable-depositoruniv3 :; PATH=${PATH} certoraRun certora/funnels/automation/StableDepositorUniV3.conf$(if $(rule), --rule $(rule),) 12 | certora-conduit-mover :; PATH=${PATH} certoraRun certora/funnels/automation/ConduitMover.conf$(if $(rule), --rule $(rule),) 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `dss-allocator` 2 | 3 | Part of this code was inspired by https://github.com/makerdao/rwa-toolkit/blob/master/src/urns/RwaUrn.sol mainly authored by livnev and https://github.com/dapphub/ds-roles/blob/master/src/roles.sol authored by DappHub. 4 | Since it should belong to the MakerDAO community the Copyright from our additions has been transferred to Dai Foundation. 5 | 6 | ## Important Update: 7 | 8 | **The funnels in this repository and their automation contracts should now be regarded as included for illustrative purposes only. In practice, other use-case specialized funnels are expected to be built.** 9 | 10 | **The deployment libraries, tests and the documentation below still use the specific included funnels (e.g DepositorUniV3, Swapper). Those parts should be considered as obsolete.** 11 | 12 | ## Overview 13 | Implementation of the allocation system, based on the [technical specification forum post](https://forum.makerdao.com/t/preliminary-technical-specification-of-the-allocation-system/20921). 14 | The conduits are implemented separately. See for example [dss-conduits](https://github.com/makerdao/dss-conduits). 15 | 16 | ![Untitled-2023-08-07-1511](https://github.com/makerdao/dss-allocator/assets/130549691/af24bcb8-5e5a-4394-8eee-a1f7d6f44341) 17 | 18 | ## Layers 19 | The system is comprised of several layers: 20 | 21 | - Core Allocation System (*green above*): 22 | - Smart contracts that can be considered a part of the Maker Core Protocol, and are immutable and present in all Allocators. 23 | - Their main role is to mint USDS (New Stable Token) and hold it (possibly with other tokens) in the `AllocatorBuffer`. 24 | - Deployment Funnels (*blue above*): 25 | - Contracts that pull funds from the `AllocatorBuffer`. 26 | - The funds can be swapped and/or deployed into AMM pools or specific conduits. 27 | - A typical setting for a funnel includes a base rate-limited contract (such as Swapper) and an automation contract on top of it (such as StableSwapper). 28 | - Conduits (*orange above*): 29 | - Yield investment singletons that support deposits and withdrawals. 30 | 31 | ## Actors 32 | The allocation system includes several actor types: 33 | 34 | - Pause Proxy: 35 | - Performs actions through spells with governance delay. 36 | - In charge of setting up the core components and the USDS minting instant access modules (DC-IAMs). 37 | - Ward of the singleton contracts (e.g RWA conduits, Coinbase Custody, `AllocatorRoles`). 38 | - AllocatorDAO Proxy: 39 | - Performs actions through a sub-spell with governance delay. 40 | - Ward of its `AllocatorVault`, `AllocatorBuffer` and funnel contracts. 41 | - In charge of adding new contracts to the funnel network (e.g Swapper, DepositorUniV3). 42 | - Can add operators to its funnel network through the `AllocatorRoles` contract. 43 | - In charge of setting rate-limiting safety parameters for operators. 44 | - Operator: 45 | - Performs actions without a spell and without governance delay. 46 | - An optional actor which is whitelisted through the `AllocatorRoles` contract to perform specified actions on the `AllocatorVault`, funnels and conduits. 47 | - Will typically be a facilitator multisig or an automation contract controlled by one (e.g `StableSwapper`, `StableDepositorUniV3`). 48 | - Keeper: 49 | - An optional actor which can be set up to trigger the automation contracts in case repetitive actions are needed (such as swapping USDS to USDC every time interval). 50 | 51 | ![Untitled (1)](https://github.com/makerdao/dss-allocator/assets/130549691/c677928b-32f4-4000-b6ed-e3798caa9c5c) 52 | 53 | ## Contracts and Configuration 54 | ### VAT Configuration 55 | 56 | Each AllocatorDAO has a unique `ilk` (collateral type) with one VAT vault set up for it. 57 | 58 | - All the `ilk`s have a shared simple [oracle](https://github.com/makerdao/dss-allocator/blob/dev/src/AllocatorOracle.sol) that just returns a fixed price of 1:1 (which multiplied by a huge amount of collateral makes sure the max debt ceiling can indeed be reached). In case it is necessary a governance spell could also increase it further. 59 | 60 | ### AllocatorVault 61 | 62 | Single contract per `ilk`, which operators can use to: 63 | 64 | - Mint (`draw`) USDS from the vault to the AllocatorBuffer. 65 | - Repay (`wipe`) USDS from the AllocatorBuffer. 66 | 67 | ### AllocatorBuffer 68 | 69 | A simple contract for the AllocatorDAO to hold funds in. 70 | 71 | - Supports approving contracts to `transferFrom` it. 72 | - Note that although the `AllocatorVault` pushes and pulls USDS to/from the `AllocatorBuffer`, it can manage other tokens as well. 73 | 74 | ### AllocatorRoles 75 | 76 | A global permissions registry, inspired by [ds-roles](https://github.com/dapphub/ds-roles). 77 | 78 | - Allows AllocatorDAOs to list operators to manage `AllocatorVault`s, funnels and conduits in a per-action resolution. 79 | - Warded by the Pause Proxy, which needs to add a new AllocatorDAO once one is onboarded. 80 | 81 | ### AllocatorRegistry 82 | 83 | A registry where each AllocatorDAO’s `AllocatorBuffer` address is listed. 84 | 85 | ### Swapper 86 | 87 | A module that pulls tokens from the `AllocatorBuffer` and sends them to be swapped at a callee contract. The resulting funds are sent back to the `AllocatorBuffer`. 88 | 89 | It enforces that: 90 | 91 | - The swap rate is not faster than a pre-configured rate. 92 | - The amount to swap each time is not larger than a pre-configured amount. 93 | - The received funds are not less than a minimal amount specified on the swap call. 94 | 95 | ### Swapper Callees 96 | 97 | Contracts that perform the actual swap and send the resulting funds to the Swapper (to be forwarded to the AllocatorBuffer). 98 | 99 | - They can be implemented on top of any DEX / swap vehicle. 100 | - An example is `SwapperCalleeUniV3`, where swaps in Uniswap V3 can be triggered. 101 | 102 | ### DepositorUniV3 103 | 104 | A primitive for depositing liquidity to Uniswap V3 in a fixed range. 105 | 106 | As the Swapper, it includes rate limit protection and is designed so facilitators and automation contracts can use it. 107 | 108 | ### VaultMinter 109 | 110 | An automation contract sample, which can be used by the AllocatorDAOs to `draw` or `wipe` from/to the `AllocatorVault`. 111 | - It can be useful for automating generation of funds from the vault to the buffer or repayment from the buffer to the vault. 112 | 113 | ### StableSwapper 114 | 115 | An automation contract, which can be used by the AllocatorDAOs to set up recurring swaps of stable tokens (e.g USDS to USDC). 116 | 117 | - In order to use it, the AllocatorDAO should list it as an operator of its `Swapper` primitive in the `AllocatorRoles` contract. 118 | - The `Swapper` primitive will rate-limit the automation contract. 119 | 120 | ### StableDepositorUniV3 121 | 122 | An automation contract sample, which can be used by the AllocatorDAOs to set up recurring deposits or withdraws. 123 | 124 | - In order to use it, the AllocatorDAO should list it as an operator of its `DepositorUniV3` primitive in the `AllocatorRoles` contract. 125 | - The `Depositor` primitive will rate-limit the automation contract. 126 | 127 | ### ConduitMover 128 | 129 | An automation contract sample, which can be used by the AllocatorDAOs to move funds between their `AllocatorBuffer` and the conduits in an automated manner. 130 | - Although there is no built-in rate limit in the transfer of funds from/to the `AllocatorBuffer` to/form the conduits, 131 | this can be useful for optimizing yield by moving funds to the destination conduit just in time for them to get processed 132 | (in case the destination conduit has an agreed upon rate limiting). 133 | - It can also be useful for automating movement of funds from the buffer in the same rate as they are swapped or withdrawn into it. 134 | 135 | ### IAllocatorConduit 136 | 137 | An interface which each Conduit should implement. 138 | 139 | ## Security Model: 140 | - AllocatorDAOs can not incur a loss of more than the debt ceiling (`line`) of their respective `ilk`. 141 | - A funnel operator (whether a facilitator or an automated contract) can not incur a loss of more than `cap` amount of funds per `era` interval for a specific configuration. This includes not being able to move funds directly to any unknown address that the AllocatorDAO Proxy did not approve. 142 | - A keeper's maximum loss must be bounded by `cap` amount of funds per `era` (as for a funnel operator) but is additionally constrainted by `lot` (or `amt0` and `amt1`) amount of funds per `hop` for a specific configuration. Moreover, a keeper's execution must guarantee a minimum amount of output tokens, defined by `req` (or `req0` and `req1`) for a specific configuration. 143 | - If a rate limit is needed for depositing or withdrawing in a specific Conduit (in order to limit the harm a rogue facilitator can cause), it is the responsibility of the Conduit itself to implement it. 144 | 145 | ## Technical Assumptions: 146 | - A `uint32` is suitable for storing timestamps or time intervals in the funnels, as the current version of the Allocation System is expected to be deprecated long before 2106. 147 | - A `uint96` is suitable for storing token amounts in the funnels, as amounts in the scale of 70B are not expected to be used. This implies that the Allocation System does not support tokens with extremely low prices. 148 | - As with most MakerDAO contracts, non standard token implementations are assumed to not be supported. As examples, this includes tokens that: 149 | * Do not have a decimals field or have more than 18 decimals. 150 | * Do not revert and instead rely on a return value. 151 | * Implement fee on transfer. 152 | * Include rebasing logic. 153 | * Implement callbacks/hooks. 154 | - In the Swapper, in case `limit.era` is zero the full cap amount can be swapped for multiple times in the same transaction because `limit.due` will be reset upon re-entry. However, this is consistent with the intended behavior, as in that case zero cooldown is explicitly defined. 155 | - In StableSwapper the keeper's minimal out value is assumed to be updated whenever `configs[src][dst]` is changed. Failing to do so may result in the swap call reverting or in taking on more slippage than intended (up to a limit controlled by `configs[src][dst].min`). 156 | - In StableDepositorUniV3 the keeper's minimal amt values are assumed to be updated whenever `configs[gem0][gem1][fee][tickLower][tickUpper]` is changed. Failing to do so may result in the deposit/withdraw call reverting or in taking on more slippage than intended (up to a limit controlled by `configs[gem0][gem1][fee][tickLower][tickUpper].req0/1`). 157 | - Deployment sanity checks are done as part of the init functions (see the `deploy` directory). 158 | - DepositorUniV3 has limits for the maximum amount of a pair of tokens that can be added or removed from the pool per era. The rate is purposefully shared between the deposit and withdraw operations (so both actions share the same capacity). 159 | - The AllocatorDAO Proxy configuring the different rate limits is assumed to know what it is doing and is allowed to set any configuration, even if one configuration collides or duplicates others. 160 | - The Allocation System assumes that the ESM threshold is set large enough prior to its deployment, so Emergency Shutdown can never be called. 161 | -------------------------------------------------------------------------------- /audit/20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sky-ecosystem/dss-allocator/6e99d87374cff66e93fe44c55d4ed240dac1c3dc/audit/20240909-ChainSecurity_MakerDAO_Allocator_Deployment_Scripts_audit.pdf -------------------------------------------------------------------------------- /audit/20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sky-ecosystem/dss-allocator/6e99d87374cff66e93fe44c55d4ed240dac1c3dc/audit/20240909-ChainSecurity_MakerDAO_Allocator_audit.pdf -------------------------------------------------------------------------------- /audit/FPS_dss-allocator_Assessment_FINAL.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sky-ecosystem/dss-allocator/6e99d87374cff66e93fe44c55d4ed240dac1c3dc/audit/FPS_dss-allocator_Assessment_FINAL.pdf -------------------------------------------------------------------------------- /audit/cantina-report-review-makerdao-dssallocator.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sky-ecosystem/dss-allocator/6e99d87374cff66e93fe44c55d4ed240dac1c3dc/audit/cantina-report-review-makerdao-dssallocator.pdf -------------------------------------------------------------------------------- /certora/AllocatorBuffer.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/AllocatorBuffer.sol", 4 | "test/mocks/GemMock.sol" 5 | ], 6 | "rule_sanity": "basic", 7 | "solc": "solc-0.8.16", 8 | "solc_optimize_map": { 9 | "AllocatorBuffer": "200", 10 | "GemMock": "0" 11 | }, 12 | "verify": "AllocatorBuffer:certora/AllocatorBuffer.spec", 13 | "parametric_contracts": [ 14 | "AllocatorBuffer" 15 | ], 16 | "wait_for_results": "all" 17 | } 18 | -------------------------------------------------------------------------------- /certora/AllocatorBuffer.spec: -------------------------------------------------------------------------------- 1 | // AllocatorBuffer.spec 2 | 3 | using GemMock as gem; 4 | 5 | methods { 6 | function wards(address) external returns (uint256) envfree; 7 | function gem.allowance(address, address) external returns (uint256) envfree; 8 | function _.approve(address, uint256) external => DISPATCHER(true) UNRESOLVED; 9 | } 10 | 11 | // Verify that each storage layout is only modified in the corresponding functions 12 | rule storageAffected(method f) { 13 | env e; 14 | 15 | address anyAddr; 16 | 17 | mathint wardsBefore = wards(anyAddr); 18 | 19 | calldataarg args; 20 | f(e, args); 21 | 22 | mathint wardsAfter = wards(anyAddr); 23 | 24 | assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function"; 25 | } 26 | 27 | // Verify correct storage changes for non reverting rely 28 | rule rely(address usr) { 29 | env e; 30 | 31 | address other; 32 | require other != usr; 33 | 34 | mathint wardsOtherBefore = wards(other); 35 | 36 | rely(e, usr); 37 | 38 | mathint wardsUsrAfter = wards(usr); 39 | mathint wardsOtherAfter = wards(other); 40 | 41 | assert wardsUsrAfter == 1, "rely did not set the wards"; 42 | assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]"; 43 | } 44 | 45 | // Verify revert rules on rely 46 | rule rely_revert(address usr) { 47 | env e; 48 | 49 | mathint wardsSender = wards(e.msg.sender); 50 | 51 | rely@withrevert(e, usr); 52 | 53 | bool revert1 = e.msg.value > 0; 54 | bool revert2 = wardsSender != 1; 55 | 56 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 57 | } 58 | 59 | // Verify correct storage changes for non reverting deny 60 | rule deny(address usr) { 61 | env e; 62 | 63 | address other; 64 | require other != usr; 65 | 66 | mathint wardsOtherBefore = wards(other); 67 | 68 | deny(e, usr); 69 | 70 | mathint wardsUsrAfter = wards(usr); 71 | mathint wardsOtherAfter = wards(other); 72 | 73 | assert wardsUsrAfter == 0, "deny did not set the wards"; 74 | assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]"; 75 | } 76 | 77 | // Verify revert rules on deny 78 | rule deny_revert(address usr) { 79 | env e; 80 | 81 | mathint wardsSender = wards(e.msg.sender); 82 | 83 | deny@withrevert(e, usr); 84 | 85 | bool revert1 = e.msg.value > 0; 86 | bool revert2 = wardsSender != 1; 87 | 88 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 89 | } 90 | 91 | // Verify correct storage changes for non reverting approve 92 | rule approve(address asset, address spender, uint256 amount) { 93 | env e; 94 | 95 | require asset == gem; 96 | 97 | approve(e, asset, spender, amount); 98 | 99 | mathint allowance = gem.allowance(currentContract, spender); 100 | 101 | assert allowance == to_mathint(amount), "approve did not set allowance to amount value"; 102 | } 103 | 104 | // Verify revert rules on approve 105 | rule approve_revert(address asset, address spender, uint256 amount) { 106 | env e; 107 | 108 | require asset == gem; 109 | 110 | mathint wardsSender = wards(e.msg.sender); 111 | 112 | approve@withrevert(e, asset, spender, amount); 113 | 114 | bool revert1 = e.msg.value > 0; 115 | bool revert2 = wardsSender != 1; 116 | 117 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 118 | } 119 | -------------------------------------------------------------------------------- /certora/AllocatorOracle.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/AllocatorOracle.sol" 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "AllocatorOracle:certora/AllocatorOracle.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/AllocatorOracle.spec: -------------------------------------------------------------------------------- 1 | // AllocatorOracle.spec 2 | 3 | methods { 4 | function peek() external returns (bytes32, bool) envfree; 5 | function read() external returns (bytes32) envfree; 6 | } 7 | 8 | // Verify correct response from peek 9 | rule peek() { 10 | bytes32 val; 11 | bool ok; 12 | val, ok = peek(); 13 | 14 | assert val == to_bytes32(10^18), "peek did not return the expected val result"; 15 | assert ok, "peek did not return the expected ok result"; 16 | } 17 | 18 | // Verify correct response from read 19 | rule read() { 20 | bytes32 val = read(); 21 | 22 | assert val == to_bytes32(10^18), "read did not return the expected result"; 23 | } 24 | -------------------------------------------------------------------------------- /certora/AllocatorRegistry.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/AllocatorRegistry.sol" 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "AllocatorRegistry:certora/AllocatorRegistry.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/AllocatorRegistry.spec: -------------------------------------------------------------------------------- 1 | // AllocatorRegistry.spec 2 | 3 | methods { 4 | function wards(address) external returns (uint256) envfree; 5 | function buffers(bytes32) external returns (address) envfree; 6 | } 7 | 8 | // Verify that each storage layout is only modified in the corresponding functions 9 | rule storageAffected(method f) { 10 | env e; 11 | 12 | address anyAddr; 13 | bytes32 anyBytes32; 14 | 15 | mathint wardsBefore = wards(anyAddr); 16 | address buffersBefore = buffers(anyBytes32); 17 | 18 | calldataarg args; 19 | f(e, args); 20 | 21 | mathint wardsAfter = wards(anyAddr); 22 | address buffersAfter = buffers(anyBytes32); 23 | 24 | assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function"; 25 | assert buffersAfter != buffersBefore => f.selector == sig:file(bytes32,bytes32,address).selector, "buffers[x] changed in an unexpected function"; 26 | } 27 | 28 | // Verify correct storage changes for non reverting rely 29 | rule rely(address usr) { 30 | env e; 31 | 32 | address other; 33 | require other != usr; 34 | 35 | mathint wardsOtherBefore = wards(other); 36 | 37 | rely(e, usr); 38 | 39 | mathint wardsUsrAfter = wards(usr); 40 | mathint wardsOtherAfter = wards(other); 41 | 42 | assert wardsUsrAfter == 1, "rely did not set the wards"; 43 | assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]"; 44 | } 45 | 46 | // Verify revert rules on rely 47 | rule rely_revert(address usr) { 48 | env e; 49 | 50 | mathint wardsSender = wards(e.msg.sender); 51 | 52 | rely@withrevert(e, usr); 53 | 54 | bool revert1 = e.msg.value > 0; 55 | bool revert2 = wardsSender != 1; 56 | 57 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 58 | } 59 | 60 | // Verify correct storage changes for non reverting deny 61 | rule deny(address usr) { 62 | env e; 63 | 64 | address other; 65 | require other != usr; 66 | 67 | mathint wardsOtherBefore = wards(other); 68 | 69 | deny(e, usr); 70 | 71 | mathint wardsUsrAfter = wards(usr); 72 | mathint wardsOtherAfter = wards(other); 73 | 74 | assert wardsUsrAfter == 0, "deny did not set the wards"; 75 | assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]"; 76 | } 77 | 78 | // Verify revert rules on deny 79 | rule deny_revert(address usr) { 80 | env e; 81 | 82 | mathint wardsSender = wards(e.msg.sender); 83 | 84 | deny@withrevert(e, usr); 85 | 86 | bool revert1 = e.msg.value > 0; 87 | bool revert2 = wardsSender != 1; 88 | 89 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 90 | } 91 | 92 | // Verify correct storage changes for non reverting file 93 | rule file(bytes32 ilk, bytes32 what, address data) { 94 | env e; 95 | 96 | bytes32 otherBytes32; 97 | require otherBytes32 != ilk; 98 | 99 | address buffersOtherBefore = buffers(otherBytes32); 100 | 101 | file(e, ilk, what, data); 102 | 103 | address buffersIlkAfter = buffers(ilk); 104 | address buffersOtherAfter = buffers(otherBytes32); 105 | 106 | assert buffersIlkAfter == data, "file did not set buffers[ilk] to data"; 107 | assert buffersOtherAfter == buffersOtherBefore, "file did not keep unchanged the rest of buffers[x]"; 108 | } 109 | 110 | // Verify revert rules on file 111 | rule file_revert(bytes32 ilk, bytes32 what, address data) { 112 | env e; 113 | 114 | mathint wardsSender = wards(e.msg.sender); 115 | 116 | file@withrevert(e, ilk, what, data); 117 | 118 | bool revert1 = e.msg.value > 0; 119 | bool revert2 = wardsSender != 1; 120 | bool revert3 = what != to_bytes32(0x6275666665720000000000000000000000000000000000000000000000000000); 121 | 122 | assert lastReverted <=> revert1 || revert2 || revert3, "Revert rules failed"; 123 | } 124 | -------------------------------------------------------------------------------- /certora/AllocatorRoles.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/AllocatorRoles.sol" 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "AllocatorRoles:certora/AllocatorRoles.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/AllocatorRoles.spec: -------------------------------------------------------------------------------- 1 | // AllocatorRoles.spec 2 | 3 | methods { 4 | function wards(address) external returns (uint256) envfree; 5 | function ilkAdmins(bytes32) external returns (address) envfree; 6 | function userRoles(bytes32, address) external returns (bytes32) envfree; 7 | function actionsRoles(bytes32, address, bytes4) external returns (bytes32) envfree; 8 | function hasUserRole(bytes32, address, uint8) external returns (bool) envfree; 9 | function hasActionRole(bytes32, address, bytes4, uint8) external returns (bool) envfree; 10 | function canCall(bytes32, address, address, bytes4) external returns (bool) envfree; 11 | } 12 | 13 | definition bitNot(uint256 input) returns uint256 = input xor max_uint256; 14 | 15 | // Verify correct response from hasUserRole 16 | rule hasUserRole(bytes32 ilk, address who, uint8 role) { 17 | bool ok = userRoles(ilk, who) & to_bytes32(assert_uint256(2^role)) != to_bytes32(0); 18 | 19 | bool ok2 = hasUserRole(ilk, who, role); 20 | 21 | assert ok2 == ok, "hasUserRole did not return the expected result"; 22 | } 23 | 24 | // Verify correct response from hasActionRole 25 | rule hasActionRole(bytes32 ilk, address target, bytes4 sign, uint8 role) { 26 | bool ok = actionsRoles(ilk, target, sign) & to_bytes32(assert_uint256(2^role)) != to_bytes32(0); 27 | 28 | bool ok2 = hasActionRole(ilk, target, sign, role); 29 | 30 | assert ok2 == ok, "hasActionRole did not return the expected result"; 31 | } 32 | 33 | // Verify that each storage layout is only modified in the corresponding functions 34 | rule storageAffected(method f) { 35 | env e; 36 | 37 | address anyAddr; 38 | bytes32 anyBytes32; 39 | bytes4 anyBytes4; 40 | 41 | mathint wardsBefore = wards(anyAddr); 42 | address ilkAdminsBefore = ilkAdmins(anyBytes32); 43 | bytes32 userRolesBefore = userRoles(anyBytes32, anyAddr); 44 | bytes32 actionsRolesBefore = actionsRoles(anyBytes32, anyAddr, anyBytes4); 45 | 46 | calldataarg args; 47 | f(e, args); 48 | 49 | mathint wardsAfter = wards(anyAddr); 50 | address ilkAdminsAfter = ilkAdmins(anyBytes32); 51 | bytes32 userRolesAfter = userRoles(anyBytes32, anyAddr); 52 | bytes32 actionsRolesAfter = actionsRoles(anyBytes32, anyAddr, anyBytes4); 53 | 54 | assert wardsAfter != wardsBefore => f.selector == sig:rely(address).selector || f.selector == sig:deny(address).selector, "wards[x] changed in an unexpected function"; 55 | assert ilkAdminsAfter != ilkAdminsBefore => f.selector == sig:setIlkAdmin(bytes32,address).selector, "ilkAdmins[x] changed in an unexpected function"; 56 | assert userRolesAfter != userRolesBefore => f.selector == sig:setUserRole(bytes32,address,uint8,bool).selector, "userRoles[x][y] changed in an unexpected function"; 57 | assert actionsRolesAfter != actionsRolesBefore => f.selector == sig:setRoleAction(bytes32,uint8,address,bytes4,bool).selector, "actionsRoles[x][y][z] changed in an unexpected function"; 58 | } 59 | 60 | // Verify correct storage changes for non reverting rely 61 | rule rely(address usr) { 62 | env e; 63 | 64 | address other; 65 | require other != usr; 66 | 67 | mathint wardsOtherBefore = wards(other); 68 | 69 | rely(e, usr); 70 | 71 | mathint wardsUsrAfter = wards(usr); 72 | mathint wardsOtherAfter = wards(other); 73 | 74 | assert wardsUsrAfter == 1, "rely did not set the wards"; 75 | assert wardsOtherAfter == wardsOtherBefore, "rely did not keep unchanged the rest of wards[x]"; 76 | } 77 | 78 | // Verify revert rules on rely 79 | rule rely_revert(address usr) { 80 | env e; 81 | 82 | mathint wardsSender = wards(e.msg.sender); 83 | 84 | rely@withrevert(e, usr); 85 | 86 | bool revert1 = e.msg.value > 0; 87 | bool revert2 = wardsSender != 1; 88 | 89 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 90 | } 91 | 92 | // Verify correct storage changes for non reverting deny 93 | rule deny(address usr) { 94 | env e; 95 | 96 | address other; 97 | require other != usr; 98 | 99 | mathint wardsOtherBefore = wards(other); 100 | 101 | deny(e, usr); 102 | 103 | mathint wardsUsrAfter = wards(usr); 104 | mathint wardsOtherAfter = wards(other); 105 | 106 | assert wardsUsrAfter == 0, "deny did not set the wards"; 107 | assert wardsOtherAfter == wardsOtherBefore, "deny did not keep unchanged the rest of wards[x]"; 108 | } 109 | 110 | // Verify revert rules on deny 111 | rule deny_revert(address usr) { 112 | env e; 113 | 114 | mathint wardsSender = wards(e.msg.sender); 115 | 116 | deny@withrevert(e, usr); 117 | 118 | bool revert1 = e.msg.value > 0; 119 | bool revert2 = wardsSender != 1; 120 | 121 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 122 | } 123 | 124 | // Verify correct storage changes for non reverting setIlkAdmin 125 | rule setIlkAdmin(bytes32 ilk, address usr) { 126 | env e; 127 | 128 | bytes32 otherBytes32; 129 | require otherBytes32 != ilk; 130 | 131 | address ilkAdminsOtherBefore = ilkAdmins(otherBytes32); 132 | 133 | setIlkAdmin(e, ilk, usr); 134 | 135 | address ilkAdminsIlkAfter = ilkAdmins(ilk); 136 | address ilkAdminsOtherAfter = ilkAdmins(otherBytes32); 137 | 138 | assert ilkAdminsIlkAfter == usr, "setIlkAdmin did not set ilkAdmins[ilk] to usr"; 139 | assert ilkAdminsOtherAfter == ilkAdminsOtherBefore, "setIlkAdmin did not keep unchanged the rest of ilkAdmins[x]"; 140 | } 141 | 142 | // Verify revert rules on setIlkAdmin 143 | rule setIlkAdmin_revert(bytes32 ilk, address usr) { 144 | env e; 145 | 146 | mathint wardsSender = wards(e.msg.sender); 147 | 148 | setIlkAdmin@withrevert(e, ilk, usr); 149 | 150 | bool revert1 = e.msg.value > 0; 151 | bool revert2 = wardsSender != 1; 152 | 153 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 154 | } 155 | 156 | // Verify correct storage changes for non reverting setUserRole 157 | rule setUserRole(bytes32 ilk, address who, uint8 role, bool enabled) { 158 | env e; 159 | 160 | bytes32 otherBytes32; 161 | address otherAddr; 162 | require otherBytes32 != ilk || otherAddr != who; 163 | 164 | bytes32 userRolesIlkWhoBefore = userRoles(ilk, who); 165 | bytes32 userRolesOtherBefore = userRoles(otherBytes32, otherAddr); 166 | uint256 mask = assert_uint256(2^role); 167 | bytes32 value = enabled ? userRolesIlkWhoBefore | to_bytes32(mask) : userRolesIlkWhoBefore & to_bytes32(bitNot(mask)); 168 | 169 | setUserRole(e, ilk, who, role, enabled); 170 | 171 | bytes32 userRolesIlkWhoAfter = userRoles(ilk, who); 172 | bytes32 userRolesOtherAfter = userRoles(otherBytes32, otherAddr); 173 | 174 | assert userRolesIlkWhoAfter == value, "setUserRole did not set userRoles[ilk][who] by the corresponding value"; 175 | assert userRolesOtherAfter == userRolesOtherBefore, "setUserRole did not keep unchanged the rest of userRoles[x][y]"; 176 | } 177 | 178 | // Verify revert rules on setUserRole 179 | rule setUserRole_revert(bytes32 ilk, address who, uint8 role, bool enabled) { 180 | env e; 181 | 182 | address ilkAuthIlk = ilkAdmins(ilk); 183 | 184 | setUserRole@withrevert(e, ilk, who, role, enabled); 185 | 186 | bool revert1 = e.msg.value > 0; 187 | bool revert2 = ilkAuthIlk != e.msg.sender; 188 | 189 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 190 | } 191 | 192 | // Verify correct storage changes for non reverting setRoleAction 193 | rule setRoleAction(bytes32 ilk, uint8 role, address target, bytes4 sign, bool enabled) { 194 | env e; 195 | 196 | bytes32 otherBytes32; 197 | address otherAddr; 198 | bytes4 otherBytes4; 199 | require otherBytes32 != ilk || otherAddr != target || otherBytes4 != sign; 200 | 201 | bytes32 actionsRolesIlkTargetSigBefore = actionsRoles(ilk, target, sign); 202 | bytes32 actionsRolesOtherBefore = actionsRoles(otherBytes32, otherAddr, otherBytes4); 203 | uint256 mask = assert_uint256(2^role); 204 | bytes32 value = enabled ? actionsRolesIlkTargetSigBefore | to_bytes32(mask) : actionsRolesIlkTargetSigBefore & to_bytes32(bitNot(mask)); 205 | 206 | setRoleAction(e, ilk, role, target, sign, enabled); 207 | 208 | bytes32 actionsRolesIlkTargetSigAfter = actionsRoles(ilk, target, sign); 209 | bytes32 actionsRolesOtherAfter = actionsRoles(otherBytes32, otherAddr, otherBytes4); 210 | 211 | assert actionsRolesIlkTargetSigAfter == value, "setRoleAction did not set actionsRoles[ilk][target][sig] by the corresponding value"; 212 | assert actionsRolesOtherAfter == actionsRolesOtherBefore, "setRoleAction did not keep unchanged the rest of actionsRoles[x][y][z]"; 213 | } 214 | 215 | // Verify revert rules on setRoleAction 216 | rule setRoleAction_revert(bytes32 ilk, uint8 role, address target, bytes4 sign, bool enabled) { 217 | env e; 218 | 219 | address ilkAuthIlk = ilkAdmins(ilk); 220 | 221 | setRoleAction@withrevert(e, ilk, role, target, sign, enabled); 222 | 223 | bool revert1 = e.msg.value > 0; 224 | bool revert2 = ilkAuthIlk != e.msg.sender; 225 | 226 | assert lastReverted <=> revert1 || revert2, "Revert rules failed"; 227 | } 228 | 229 | // Verify correct response from canCall 230 | rule canCall(bytes32 ilk, address caller, address target, bytes4 sign) { 231 | bool ok = userRoles(ilk, caller) & actionsRoles(ilk, target, sign) != to_bytes32(0); 232 | 233 | bool ok2 = canCall(ilk, caller, target, sign); 234 | 235 | assert ok2 == ok, "canCall did not return the expected result"; 236 | } 237 | -------------------------------------------------------------------------------- /certora/AllocatorVault.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/AllocatorVault.sol", 4 | "src/AllocatorRoles.sol", 5 | "test/mocks/VatMock.sol", 6 | "test/mocks/JugMock.sol", 7 | "test/mocks/UsdsJoinMock.sol", 8 | "test/mocks/UsdsMock.sol" 9 | ], 10 | "link": [ 11 | "AllocatorVault:roles=AllocatorRoles", 12 | "AllocatorVault:vat=VatMock", 13 | "AllocatorVault:jug=JugMock", 14 | "AllocatorVault:usdsJoin=UsdsJoinMock", 15 | "AllocatorVault:usds=UsdsMock", 16 | "JugMock:vat=VatMock", 17 | "UsdsJoinMock:vat=VatMock", 18 | "UsdsJoinMock:usds=UsdsMock" 19 | ], 20 | "rule_sanity": "basic", 21 | "solc": "solc-0.8.16", 22 | "solc_optimize_map": { 23 | "AllocatorVault": "200", 24 | "AllocatorRoles": "200", 25 | "VatMock": "0", 26 | "JugMock": "0", 27 | "UsdsJoinMock": "0", 28 | "UsdsMock": "0" 29 | }, 30 | "verify": "AllocatorVault:certora/AllocatorVault.spec", 31 | "parametric_contracts": [ 32 | "AllocatorVault" 33 | ], 34 | "multi_assert_check": true, 35 | "wait_for_results": "all" 36 | } 37 | -------------------------------------------------------------------------------- /certora/funnels/Auxiliar.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | contract Auxiliar { 6 | function getHash(address addr, int24 tickLower, int24 tickUpper) external pure returns (bytes32 hashC) { 7 | hashC = keccak256(abi.encodePacked(addr, tickLower, tickUpper)); 8 | } 9 | 10 | function decode(bytes calldata data) external pure returns (address gem0, address gem1, uint24 fee) { 11 | (gem0, gem1, fee) = abi.decode(data, (address, address, uint24)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /certora/funnels/DepositorUniV3.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/DepositorUniV3.sol", 4 | "src/AllocatorRoles.sol", 5 | "test/mocks/PoolUniV3Mock.sol", 6 | "test/mocks/Gem0Mock.sol", 7 | "test/mocks/Gem1Mock.sol", 8 | "certora/funnels/Auxiliar.sol" 9 | ], 10 | "link": [ 11 | "DepositorUniV3:roles=AllocatorRoles" 12 | ], 13 | "rule_sanity": "basic", 14 | "solc": "solc-0.8.16", 15 | "solc_optimize_map": { 16 | "DepositorUniV3": "200", 17 | "AllocatorRoles": "200", 18 | "PoolUniV3Mock": "0", 19 | "Gem0Mock": "0", 20 | "Gem1Mock": "0", 21 | "Auxiliar": "0" 22 | }, 23 | "verify": "DepositorUniV3:certora/funnels/DepositorUniV3.spec", 24 | "parametric_contracts": [ 25 | "DepositorUniV3" 26 | ], 27 | "wait_for_results": "all" 28 | } 29 | -------------------------------------------------------------------------------- /certora/funnels/Swapper.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/Swapper.sol", 4 | "src/AllocatorRoles.sol", 5 | "test/mocks/Gem0Mock.sol", 6 | "test/mocks/Gem1Mock.sol", 7 | "test/mocks/CalleeMock.sol" 8 | ], 9 | "link": [ 10 | "Swapper:roles=AllocatorRoles" 11 | ], 12 | "rule_sanity": "basic", 13 | "solc": "solc-0.8.16", 14 | "solc_optimize_map": { 15 | "Swapper": "200", 16 | "AllocatorRoles": "200", 17 | "Gem0Mock": "0", 18 | "Gem1Mock": "0", 19 | "CalleeMock": "0" 20 | }, 21 | "verify": "Swapper:certora/funnels/Swapper.spec", 22 | "parametric_contracts": [ 23 | "Swapper" 24 | ], 25 | "wait_for_results": "all" 26 | } 27 | -------------------------------------------------------------------------------- /certora/funnels/automation/ConduitMover.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/automation/ConduitMover.sol" 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "ConduitMover:certora/funnels/automation/ConduitMover.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/funnels/automation/StableDepositorUniV3.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/automation/StableDepositorUniV3.sol", 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "StableDepositorUniV3:certora/funnels/automation/StableDepositorUniV3.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/funnels/automation/StableSwapper.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/automation/StableSwapper.sol", 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "StableSwapper:certora/funnels/automation/StableSwapper.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /certora/funnels/automation/VaultMinter.conf: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "src/funnels/automation/VaultMinter.sol" 4 | ], 5 | "rule_sanity": "basic", 6 | "solc": "solc-0.8.16", 7 | "solc_optimize": "200", 8 | "verify": "VaultMinter:certora/funnels/automation/VaultMinter.spec", 9 | "wait_for_results": "all" 10 | } 11 | -------------------------------------------------------------------------------- /deploy/AllocatorDeploy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | import { ScriptTools } from "dss-test/ScriptTools.sol"; 20 | 21 | import { AllocatorOracle } from "src/AllocatorOracle.sol"; 22 | import { AllocatorRoles } from "src/AllocatorRoles.sol"; 23 | import { AllocatorRegistry } from "src/AllocatorRegistry.sol"; 24 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 25 | import { AllocatorVault } from "src/AllocatorVault.sol"; 26 | 27 | import { AllocatorSharedInstance, AllocatorIlkInstance } from "./AllocatorInstances.sol"; 28 | 29 | library AllocatorDeploy { 30 | 31 | // Note: owner is assumed to be the pause proxy 32 | function deployShared( 33 | address deployer, 34 | address owner 35 | ) internal returns (AllocatorSharedInstance memory sharedInstance) { 36 | address _oracle = address(new AllocatorOracle()); 37 | 38 | address _roles = address(new AllocatorRoles()); 39 | ScriptTools.switchOwner(_roles, deployer, owner); 40 | 41 | address _registry = address(new AllocatorRegistry()); 42 | ScriptTools.switchOwner(_registry, deployer, owner); 43 | 44 | sharedInstance.oracle = _oracle; 45 | sharedInstance.roles = _roles; 46 | sharedInstance.registry = _registry; 47 | } 48 | 49 | // Note: owner is assumed to be the pause proxy, allocator proxy will receive ownerships on init 50 | function deployIlk( 51 | address deployer, 52 | address owner, 53 | address roles, 54 | bytes32 ilk, 55 | address usdsJoin 56 | ) internal returns (AllocatorIlkInstance memory ilkInstance) { 57 | address _buffer = address(new AllocatorBuffer()); 58 | ScriptTools.switchOwner(_buffer, deployer, owner); 59 | ilkInstance.buffer = _buffer; 60 | 61 | address _vault = address(new AllocatorVault(roles, _buffer, ilk, usdsJoin)); 62 | ScriptTools.switchOwner(_vault, deployer, owner); 63 | ilkInstance.vault = _vault; 64 | 65 | ilkInstance.owner = owner; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /deploy/AllocatorInit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity >=0.8.0; 18 | 19 | import { ScriptTools } from "dss-test/ScriptTools.sol"; 20 | import { DssInstance } from "dss-test/MCD.sol"; 21 | import { AllocatorSharedInstance, AllocatorIlkInstance } from "./AllocatorInstances.sol"; 22 | 23 | interface IlkRegistryLike { 24 | function put( 25 | bytes32 _ilk, 26 | address _join, 27 | address _gem, 28 | uint256 _dec, 29 | uint256 _class, 30 | address _pip, 31 | address _xlip, 32 | string calldata _name, 33 | string calldata _symbol 34 | ) external; 35 | } 36 | 37 | interface RolesLike { 38 | function setIlkAdmin(bytes32, address) external; 39 | } 40 | 41 | interface RegistryLike { 42 | function file(bytes32, bytes32, address) external; 43 | } 44 | 45 | interface VaultLike { 46 | function ilk() external view returns (bytes32); 47 | function roles() external view returns (address); 48 | function buffer() external view returns (address); 49 | function vat() external view returns (address); 50 | function usds() external view returns (address); 51 | function file(bytes32, address) external; 52 | } 53 | 54 | interface BufferLike { 55 | function approve(address, address, uint256) external; 56 | } 57 | 58 | interface AutoLineLike { 59 | function setIlk(bytes32, uint256, uint256, uint256) external; 60 | } 61 | 62 | struct AllocatorIlkConfig { 63 | bytes32 ilk; 64 | uint256 duty; 65 | uint256 gap; 66 | uint256 maxLine; 67 | uint256 ttl; 68 | address allocatorProxy; 69 | address ilkRegistry; 70 | } 71 | 72 | function bytes32ToStr(bytes32 _bytes32) pure returns (string memory) { 73 | uint256 len; 74 | while(len < 32 && _bytes32[len] != 0) len++; 75 | bytes memory bytesArray = new bytes(len); 76 | for (uint256 i; i < len; i++) { 77 | bytesArray[i] = _bytes32[i]; 78 | } 79 | return string(bytesArray); 80 | } 81 | 82 | library AllocatorInit { 83 | uint256 constant WAD = 10 ** 18; 84 | uint256 constant RAY = 10 ** 27; 85 | 86 | uint256 constant RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027; 87 | 88 | function initShared( 89 | DssInstance memory dss, 90 | AllocatorSharedInstance memory sharedInstance 91 | ) internal { 92 | dss.chainlog.setAddress("ALLOCATOR_ROLES", sharedInstance.roles); 93 | dss.chainlog.setAddress("ALLOCATOR_REGISTRY", sharedInstance.registry); 94 | } 95 | 96 | // Please note this should be executed by the pause proxy 97 | function initIlk( 98 | DssInstance memory dss, 99 | AllocatorSharedInstance memory sharedInstance, 100 | AllocatorIlkInstance memory ilkInstance, 101 | AllocatorIlkConfig memory cfg 102 | ) internal { 103 | bytes32 ilk = cfg.ilk; 104 | 105 | // Sanity checks 106 | require(VaultLike(ilkInstance.vault).ilk() == ilk, "AllocatorInit/vault-ilk-mismatch"); 107 | require(VaultLike(ilkInstance.vault).roles() == sharedInstance.roles, "AllocatorInit/vault-roles-mismatch"); 108 | require(VaultLike(ilkInstance.vault).buffer() == ilkInstance.buffer, "AllocatorInit/vault-buffer-mismatch"); 109 | require(VaultLike(ilkInstance.vault).vat() == address(dss.vat), "AllocatorInit/vault-vat-mismatch"); 110 | // Once usdsJoin is in the chainlog and adapted to dss-test should also check against it 111 | 112 | // Onboard the ilk 113 | dss.vat.init(ilk); 114 | dss.jug.init(ilk); 115 | 116 | require((cfg.duty >= RAY) && (cfg.duty <= RATES_ONE_HUNDRED_PCT), "AllocatorInit/ilk-duty-out-of-bounds"); 117 | dss.jug.file(ilk, "duty", cfg.duty); 118 | 119 | dss.vat.file(ilk, "line", cfg.gap); 120 | dss.vat.file("Line", dss.vat.Line() + cfg.gap); 121 | AutoLineLike(dss.chainlog.getAddress("MCD_IAM_AUTO_LINE")).setIlk(ilk, cfg.maxLine, cfg.gap, cfg.ttl); 122 | 123 | dss.spotter.file(ilk, "pip", sharedInstance.oracle); 124 | dss.spotter.file(ilk, "mat", RAY); 125 | dss.spotter.poke(ilk); 126 | 127 | // Add buffer to registry 128 | RegistryLike(sharedInstance.registry).file(ilk, "buffer", ilkInstance.buffer); 129 | 130 | // Initiate the allocator vault 131 | dss.vat.slip(ilk, ilkInstance.vault, int256(10**12 * WAD)); 132 | dss.vat.grab(ilk, ilkInstance.vault, ilkInstance.vault, address(0), int256(10**12 * WAD), 0); 133 | 134 | VaultLike(ilkInstance.vault).file("jug", address(dss.jug)); 135 | 136 | // Allow vault to pull funds from the buffer 137 | BufferLike(ilkInstance.buffer).approve(VaultLike(ilkInstance.vault).usds(), ilkInstance.vault, type(uint256).max); 138 | 139 | // Set the allocator proxy as the ilk admin instead of the Pause Proxy 140 | RolesLike(sharedInstance.roles).setIlkAdmin(ilk, cfg.allocatorProxy); 141 | 142 | // Move ownership of the ilk contracts to the allocator proxy 143 | ScriptTools.switchOwner(ilkInstance.vault, ilkInstance.owner, cfg.allocatorProxy); 144 | ScriptTools.switchOwner(ilkInstance.buffer, ilkInstance.owner, cfg.allocatorProxy); 145 | 146 | // Add allocator-specific contracts to changelog 147 | string memory ilkString = ScriptTools.ilkToChainlogFormat(ilk); 148 | dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked(ilkString, "_VAULT"))), ilkInstance.vault); 149 | dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked(ilkString, "_BUFFER"))), ilkInstance.buffer); 150 | dss.chainlog.setAddress(ScriptTools.stringToBytes32(string(abi.encodePacked("PIP_", ilkString))), sharedInstance.oracle); 151 | 152 | // Add to ilk registry 153 | IlkRegistryLike(cfg.ilkRegistry).put({ 154 | _ilk : ilk, 155 | _join : address(0), 156 | _gem : address(0), 157 | _dec : 0, 158 | _class : 5, // RWAs are class 3, D3Ms and Teleport are class 4 159 | _pip : sharedInstance.oracle, 160 | _xlip : address(0), 161 | _name : bytes32ToStr(ilk), 162 | _symbol : bytes32ToStr(ilk) 163 | }); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /deploy/AllocatorInstances.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity >=0.8.0; 18 | 19 | struct AllocatorSharedInstance { 20 | address oracle; 21 | address roles; 22 | address registry; 23 | } 24 | 25 | struct AllocatorIlkInstance { 26 | address owner; 27 | address vault; 28 | address buffer; 29 | } 30 | -------------------------------------------------------------------------------- /deploy/funnels/AllocatorFunnelDeploy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | import { ScriptTools } from "dss-test/ScriptTools.sol"; 20 | 21 | import { Swapper } from "src/funnels/Swapper.sol"; 22 | import { DepositorUniV3 } from "src/funnels/DepositorUniV3.sol"; 23 | import { VaultMinter } from "src/funnels/automation/VaultMinter.sol"; 24 | import { StableSwapper } from "src/funnels/automation/StableSwapper.sol"; 25 | import { StableDepositorUniV3 } from "src/funnels/automation/StableDepositorUniV3.sol"; 26 | import { ConduitMover } from "src/funnels/automation/ConduitMover.sol"; 27 | 28 | import { AllocatorIlkFunnelInstance } from "./AllocatorFunnelInstance.sol"; 29 | 30 | library AllocatorFunnelDeploy { 31 | 32 | // Note: owner is assumed to be the allocator proxy 33 | function deployIlkFunnel( 34 | address deployer, 35 | address owner, 36 | address roles, 37 | bytes32 ilk, 38 | address uniV3Factory, 39 | address vault, 40 | address buffer 41 | ) internal returns (AllocatorIlkFunnelInstance memory ilkFunnelInstance) { 42 | address _swapper = address(new Swapper(roles, ilk, buffer)); 43 | ScriptTools.switchOwner(_swapper, deployer, owner); 44 | ilkFunnelInstance.swapper = _swapper; 45 | 46 | address _depositorUniV3 = address(new DepositorUniV3(roles, ilk, uniV3Factory, buffer)); 47 | ScriptTools.switchOwner(_depositorUniV3, deployer, owner); 48 | ilkFunnelInstance.depositorUniV3 = _depositorUniV3; 49 | 50 | { 51 | address _vaultMinter = address(new VaultMinter(vault)); 52 | ScriptTools.switchOwner(_vaultMinter, deployer, owner); 53 | ilkFunnelInstance.vaultMinter = _vaultMinter; 54 | } 55 | 56 | { 57 | address _stableSwapper = address(new StableSwapper(_swapper)); 58 | ScriptTools.switchOwner(_stableSwapper, deployer, owner); 59 | ilkFunnelInstance.stableSwapper = _stableSwapper; 60 | } 61 | 62 | { 63 | address _stableDepositorUniV3 = address(new StableDepositorUniV3(_depositorUniV3)); 64 | ScriptTools.switchOwner(_stableDepositorUniV3, deployer, owner); 65 | ilkFunnelInstance.stableDepositorUniV3 = _stableDepositorUniV3; 66 | } 67 | 68 | { 69 | address _conduitMover = address(new ConduitMover(ilk, buffer)); 70 | ScriptTools.switchOwner(_conduitMover, deployer, owner); 71 | ilkFunnelInstance.conduitMover = _conduitMover; 72 | } 73 | 74 | ilkFunnelInstance.owner = owner; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /deploy/funnels/AllocatorFunnelInit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity >=0.8.0; 18 | 19 | import { AllocatorSharedInstance, AllocatorIlkInstance } from "deploy/AllocatorInstances.sol"; 20 | import { AllocatorIlkFunnelInstance } from "./AllocatorFunnelInstance.sol"; 21 | 22 | interface WardsLike { 23 | function rely(address) external; 24 | } 25 | 26 | interface RolesLike { 27 | function setUserRole(bytes32, address, uint8, bool) external; 28 | function setRoleAction(bytes32, uint8, address, bytes4, bool) external; 29 | } 30 | 31 | interface VaultLike { 32 | function draw(uint256) external; 33 | function wipe(uint256) external; 34 | } 35 | 36 | interface BufferLike { 37 | function approve(address, address, uint256) external; 38 | } 39 | 40 | interface SwapperLike { 41 | function roles() external view returns (address); 42 | function ilk() external view returns (bytes32); 43 | function buffer() external view returns (address); 44 | function swap(address, address, uint256, uint256, address, bytes calldata) external returns (uint256); 45 | } 46 | 47 | interface DepositorUniV3Like { 48 | struct LiquidityParams { 49 | address gem0; 50 | address gem1; 51 | uint24 fee; 52 | int24 tickLower; 53 | int24 tickUpper; 54 | uint128 liquidity; 55 | uint256 amt0Desired; 56 | uint256 amt1Desired; 57 | uint256 amt0Min; 58 | uint256 amt1Min; 59 | } 60 | 61 | struct CollectParams { 62 | address gem0; 63 | address gem1; 64 | uint24 fee; 65 | int24 tickLower; 66 | int24 tickUpper; 67 | } 68 | 69 | function roles() external view returns (address); 70 | function ilk() external view returns (bytes32); 71 | function uniV3Factory() external view returns (address); 72 | function buffer() external view returns (address); 73 | function deposit(LiquidityParams memory) external returns (uint128, uint256, uint256); 74 | function withdraw(LiquidityParams memory, bool) external returns (uint128, uint256, uint256, uint256, uint256); 75 | function collect(CollectParams memory) external returns (uint256, uint256); 76 | } 77 | 78 | interface VaultMinterLike { 79 | function vault() external view returns (address); 80 | } 81 | 82 | interface StableSwapperLike { 83 | function swapper() external view returns (address); 84 | } 85 | 86 | interface StableDepositorUniV3Like { 87 | function depositor() external view returns (address); 88 | } 89 | 90 | interface ConduitMoverLike { 91 | function ilk() external view returns (bytes32); 92 | function buffer() external view returns (address); 93 | } 94 | 95 | interface KissLike { 96 | function kiss(address) external; 97 | } 98 | 99 | struct AllocatorIlkFunnelConfig { 100 | bytes32 ilk; 101 | address allocatorProxy; 102 | uint8 facilitatorRole; 103 | uint8 automationRole; 104 | address[] facilitators; 105 | address[] vaultMinterKeepers; 106 | address[] stableSwapperKeepers; 107 | address[] stableDepositorUniV3Keepers; 108 | address[] conduitMoverKeepers; 109 | address[] swapTokens; 110 | address[] depositTokens; 111 | address uniV3Factory; 112 | } 113 | 114 | library AllocatorFunnelInit { 115 | 116 | // Please note this should be executed by the allocator proxy 117 | function initIlkFunnel( 118 | AllocatorSharedInstance memory sharedInstance, 119 | AllocatorIlkInstance memory ilkInstance, 120 | AllocatorIlkFunnelInstance memory ilkFunnelInstance, 121 | AllocatorIlkFunnelConfig memory cfg 122 | ) internal { 123 | bytes32 ilk = cfg.ilk; 124 | 125 | require(SwapperLike(ilkFunnelInstance.swapper).roles() == sharedInstance.roles, "AllocatorInit/swapper-roles-mismatch"); 126 | require(SwapperLike(ilkFunnelInstance.swapper).ilk() == ilk, "AllocatorInit/swapper-ilk-mismatch"); 127 | require(SwapperLike(ilkFunnelInstance.swapper).buffer() == ilkInstance.buffer, "AllocatorInit/swapper-buffer-mismatch"); 128 | 129 | require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).roles() == sharedInstance.roles, "AllocatorInit/depositorUniV3-roles-mismatch"); 130 | require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).ilk() == ilk, "AllocatorInit/depositorUniV3-ilk-mismatch"); 131 | require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).uniV3Factory() == cfg.uniV3Factory, "AllocatorInit/depositorUniV3-uniV3Factory-mismatch"); 132 | require(DepositorUniV3Like(ilkFunnelInstance.depositorUniV3).buffer() == ilkInstance.buffer, "AllocatorInit/depositorUniV3-buffer-mismatch"); 133 | 134 | require(VaultMinterLike(ilkFunnelInstance.vaultMinter).vault() == ilkInstance.vault, "AllocatorInit/vaultMinter-vault-mismatch"); 135 | 136 | require(StableSwapperLike(ilkFunnelInstance.stableSwapper).swapper() == ilkFunnelInstance.swapper, "AllocatorInit/stableSwapper-swapper-mismatch"); 137 | require(StableDepositorUniV3Like(ilkFunnelInstance.stableDepositorUniV3).depositor() == ilkFunnelInstance.depositorUniV3, "AllocatorInit/stableDepositorUniV3-depositorUniV3-mismatch"); 138 | 139 | require(ConduitMoverLike(ilkFunnelInstance.conduitMover).ilk() == ilk, "AllocatorInit/conduitMover-ilk-mismatch"); 140 | require(ConduitMoverLike(ilkFunnelInstance.conduitMover).buffer() == ilkInstance.buffer, "AllocatorInit/conduitMover-buffer-mismatch"); 141 | 142 | // Allow vault and funnels to pull funds from the buffer 143 | for(uint256 i = 0; i < cfg.swapTokens.length; i++) { 144 | BufferLike(ilkInstance.buffer).approve(cfg.swapTokens[i], ilkFunnelInstance.swapper, type(uint256).max); 145 | } 146 | for(uint256 i = 0; i < cfg.depositTokens.length; i++) { 147 | BufferLike(ilkInstance.buffer).approve(cfg.depositTokens[i], ilkFunnelInstance.depositorUniV3, type(uint256).max); 148 | } 149 | 150 | // Allow the facilitators to operate on the vault and funnels directly 151 | for(uint256 i = 0; i < cfg.facilitators.length; i++) { 152 | RolesLike(sharedInstance.roles).setUserRole(ilk, cfg.facilitators[i], cfg.facilitatorRole, true); 153 | } 154 | 155 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkInstance.vault, VaultLike.draw.selector, true); 156 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkInstance.vault, VaultLike.wipe.selector, true); 157 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.swapper, SwapperLike.swap.selector, true); 158 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.deposit.selector, true); 159 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.withdraw.selector, true); 160 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.facilitatorRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.collect.selector, true); 161 | 162 | // Allow the automation contracts to operate on the funnels 163 | RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.vaultMinter, cfg.automationRole, true); 164 | RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.stableSwapper, cfg.automationRole, true); 165 | RolesLike(sharedInstance.roles).setUserRole(ilk, ilkFunnelInstance.stableDepositorUniV3, cfg.automationRole, true); 166 | 167 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkInstance.vault, VaultLike.draw.selector, true); 168 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkInstance.vault, VaultLike.wipe.selector, true); 169 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.swapper, SwapperLike.swap.selector, true); 170 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.deposit.selector, true); 171 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.withdraw.selector, true); 172 | RolesLike(sharedInstance.roles).setRoleAction(ilk, cfg.automationRole, ilkFunnelInstance.depositorUniV3, DepositorUniV3Like.collect.selector, true); 173 | 174 | // Allow facilitator to set configurations in the automation contracts 175 | for(uint256 i = 0; i < cfg.facilitators.length; i++) { 176 | WardsLike(ilkFunnelInstance.vaultMinter).rely(cfg.facilitators[i]); 177 | WardsLike(ilkFunnelInstance.stableSwapper).rely(cfg.facilitators[i]); 178 | WardsLike(ilkFunnelInstance.stableDepositorUniV3).rely(cfg.facilitators[i]); 179 | WardsLike(ilkFunnelInstance.conduitMover).rely(cfg.facilitators[i]); 180 | } 181 | 182 | // Add keepers to the automation contracts 183 | for(uint256 i = 0; i < cfg.vaultMinterKeepers.length; i++) { 184 | KissLike(ilkFunnelInstance.vaultMinter).kiss(cfg.vaultMinterKeepers[i]); 185 | } 186 | for(uint256 i = 0; i < cfg.stableSwapperKeepers.length; i++) { 187 | KissLike(ilkFunnelInstance.stableSwapper).kiss(cfg.stableSwapperKeepers[i]); 188 | } 189 | for(uint256 i = 0; i < cfg.stableDepositorUniV3Keepers.length; i++) { 190 | KissLike(ilkFunnelInstance.stableDepositorUniV3).kiss(cfg.stableDepositorUniV3Keepers[i]); 191 | } 192 | for(uint256 i = 0; i < cfg.conduitMoverKeepers.length; i++) { 193 | KissLike(ilkFunnelInstance.conduitMover).kiss(cfg.conduitMoverKeepers[i]); 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /deploy/funnels/AllocatorFunnelInstance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity >=0.8.0; 18 | 19 | struct AllocatorIlkFunnelInstance { 20 | address owner; 21 | address swapper; 22 | address depositorUniV3; 23 | address vaultMinter; 24 | address stableSwapper; 25 | address stableDepositorUniV3; 26 | address conduitMover; 27 | } 28 | -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = "src" 3 | out = "out" 4 | libs = ["lib"] 5 | solc = "0.8.16" 6 | optimizer = true 7 | optimizer_runs = 200 8 | verbosity = 1 9 | 10 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config 11 | -------------------------------------------------------------------------------- /script/funnels/automation/run_conduit_mover.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Usage: ./run_conduit_mover.sh $CHAINID $CONDUIT_MOVER_ADDR $FROM_BLOCK 4 | # Example goerli usage: ./run_conduit_mover.sh 5 0x04e02dEa98410758e52cd0c47F07d9cc0fb15566 9440653 5 | 6 | set -e 7 | 8 | CHAINID=$1 9 | CONDUIT_MOVER=$2 10 | FROM_BLOCK=${3:-"earliest"} 11 | 12 | [[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; } 13 | 14 | SET_CONFIG_LOG="SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot)" 15 | MOVE_SIG="move(address from, address to, address gem)" 16 | 17 | JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $CONDUIT_MOVER "$SET_CONFIG_LOG" --json) 18 | echo $JSON | jq -c '.[]' | while read i; do 19 | from=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]")) 20 | to=$( cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]")) 21 | gem=$( cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[3]")) 22 | 23 | params="$from $to $gem" 24 | var="handled_${params// /_}" 25 | if [ -z "${!var}" ]; then 26 | declare handled_${params// /_}=1 27 | else 28 | continue 29 | fi 30 | 31 | cfg=$(cast call $CONDUIT_MOVER "configs(address,address,address)(uint64,uint32,uint32,uint128)" $params) 32 | num=$(echo $cfg | cut -d" " -f1) 33 | 34 | if (( num > 0 )); then 35 | echo "Num=$num. Moving $gem from conduit $from to conduit $to..." 36 | gas=$(cast estimate $CONDUIT_MOVER "$MOVE_SIG" $params || true) 37 | [[ -z "$gas" ]] && { continue; } 38 | cast send --gas-limit $gas $CONDUIT_MOVER "$MOVE_SIG" $params 39 | fi 40 | done 41 | -------------------------------------------------------------------------------- /script/funnels/automation/run_stable_depositor.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Usage: ./run_stable_depositor.sh $CHAINID $STABLE_DEPOSITOR_ADDR $FROM_BLOCK 4 | # Example goerli usage: ./run_stable_depositor.sh 5 0x61928e1813c8883D14a75f31F3daeE53929A45DE 9422770 5 | 6 | set -e 7 | 8 | CHAINID=$1 9 | STABLE_DEPOSITOR=$2 10 | FROM_BLOCK=${3:-"earliest"} 11 | 12 | [[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; } 13 | 14 | SET_CONFIG_LOG="SetConfig(address indexed gem0, address indexed gem1, uint24 indexed fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1)" 15 | DEPOSIT_SIG="deposit(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)" 16 | WITHDRAW_SIG="withdraw(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min)" 17 | 18 | JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $STABLE_DEPOSITOR "$SET_CONFIG_LOG" --json) 19 | echo $JSON | jq -c '.[]' | while read i; do 20 | gem0=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]")) 21 | gem1=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]")) 22 | fee=$(cast abi-decode --input "x(uint24)" $(echo $i | jq -r ".topics[3]")) 23 | data=$(cast abi-decode --input "x(int24,int24)" $(echo $i | jq -r ".data")) 24 | tickLower=$(echo $data | cut -d" " -f1) 25 | tickUpper=$(echo $data | cut -d" " -f2) 26 | 27 | params="$gem0 $gem1 $fee $tickLower $tickUpper" 28 | var="handled_${params//[- ]/_}" 29 | if [ -z "${!var}" ]; then 30 | declare handled_${params//[- ]/_}=1 31 | else 32 | continue 33 | fi 34 | 35 | cfg_calldata=$(cast calldata "configs(address,address,uint24,int24,int24)" $params) 36 | # Note that we run `cast call` using the raw calldata to avoid issues with negative arguments 37 | cfg=$(cast call $STABLE_DEPOSITOR $cfg_calldata) 38 | decoded_cfg=$(cast abi-decode --input "x(int32,uint32,uint96,uint96,uint96,uint96,uint32)" $cfg) 39 | num=$(echo $decoded_cfg | cut -d" " -f1) 40 | 41 | if (( num > 0 )); then 42 | echo "Num=$num. Depositing into ($gem0, $gem1, $fee) pool..." 43 | sig=$DEPOSIT_SIG 44 | elif (( num < 0 )); then 45 | echo "Num=$num. Withdrawing from ($gem0, $gem1, $fee) pool..." 46 | sig=$WITHDRAW_SIG 47 | fi 48 | 49 | if (( num )); then 50 | calldata=$(cast calldata "$sig" $params 0 0) 51 | # Note that we run `cast estimate` and `cast send` using the raw calldata to avoid issues with negative arguments 52 | gas=$(cast estimate $STABLE_DEPOSITOR $calldata || true) 53 | [[ -z "$gas" ]] && { continue; } 54 | cast send --gas-limit $gas $STABLE_DEPOSITOR $calldata 55 | fi 56 | done 57 | -------------------------------------------------------------------------------- /script/funnels/automation/run_stable_swapper.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Usage: ./run_stable_swapper.sh $CHAINID $STABLE_SWAPPER_ADDR $CALLEE_ADDR $POOL_FEE $FROM_BLOCK 4 | # Example goerli usage: ./run_stable_swapper.sh 5 0x4b4271cA5980a436972BEc4ad9870f773e2b3e11 0x8963f53392D35a6c9939804a924058aB981363e4 500 9416503 5 | 6 | set -e 7 | 8 | CHAINID=$1 9 | STABLE_SWAPPER=$2 10 | CALLEE=$3 11 | POOL_FEE=$4 12 | FROM_BLOCK=${5:-"earliest"} 13 | 14 | [[ "$ETH_RPC_URL" && "$(cast chain-id)" == "$CHAINID" ]] || { echo -e "Please set a ETH_RPC_URL pointing to chainId $CHAINID"; exit 1; } 15 | 16 | SET_CONFIG_LOG="SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req)" 17 | SWAP_SIG="swap(address src, address dst, uint256 minOut, address callee, bytes calldata data)" 18 | 19 | JSON=$(cast logs --from-block $FROM_BLOCK --to-block latest --address $STABLE_SWAPPER "$SET_CONFIG_LOG" --json) 20 | echo $JSON | jq -c '.[]' | while read i; do 21 | src=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[1]")) 22 | dst=$(cast abi-decode --input "x(address)" $(echo $i | jq -r ".topics[2]")) 23 | 24 | var="handled_${src}_${dst}" 25 | if [ -z "${!var}" ]; then 26 | declare handled_${src}_${dst}=1 27 | else 28 | continue 29 | fi 30 | 31 | cfg=$(cast call $STABLE_SWAPPER "configs(address,address)(uint128,uint32,uint32,uint96,uint96)" $src $dst) 32 | num=$(echo $cfg | cut -d" " -f1) 33 | 34 | if (( num > 0 )); then 35 | echo "Num=$num. Swapping from $src to $dst..." 36 | data="$(cast concat-hex $src $(printf "%06X" $(cast to-hex $POOL_FEE)) $dst)" 37 | gas=$(cast estimate $STABLE_SWAPPER "$SWAP_SIG" $src $dst 0 $CALLEE $data || true) 38 | [[ -z "$gas" ]] && { continue; } 39 | cast send --gas-limit $gas $STABLE_SWAPPER "$SWAP_SIG" $src $dst 0 $CALLEE $data 40 | fi 41 | done 42 | -------------------------------------------------------------------------------- /src/AllocatorBuffer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface GemLike { 20 | function approve(address, uint256) external; 21 | } 22 | 23 | contract AllocatorBuffer { 24 | // --- storage variables --- 25 | 26 | mapping(address => uint256) public wards; 27 | 28 | // --- events --- 29 | 30 | event Rely(address indexed usr); 31 | event Deny(address indexed usr); 32 | event Approve(address indexed asset, address indexed spender, uint256 amount); 33 | 34 | // --- modifiers --- 35 | 36 | modifier auth() { 37 | require(wards[msg.sender] == 1, "AllocatorBuffer/not-authorized"); 38 | _; 39 | } 40 | 41 | // --- constructor --- 42 | 43 | constructor() { 44 | wards[msg.sender] = 1; 45 | emit Rely(msg.sender); 46 | } 47 | 48 | // --- administration --- 49 | 50 | function rely(address usr) external auth { 51 | wards[usr] = 1; 52 | emit Rely(usr); 53 | } 54 | 55 | function deny(address usr) external auth { 56 | wards[usr] = 0; 57 | emit Deny(usr); 58 | } 59 | 60 | // --- functions --- 61 | 62 | function approve(address asset, address spender, uint256 amount) external auth { 63 | GemLike(asset).approve(spender, amount); 64 | emit Approve(asset, spender, amount); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/AllocatorOracle.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | contract AllocatorOracle { 20 | uint256 internal constant WAD = 10**18; // For 1:1 price 21 | 22 | /** 23 | @notice Return value and status of the oracle 24 | @return val PRICE constant 25 | @return ok always true 26 | */ 27 | function peek() public pure returns (bytes32 val, bool ok) { 28 | val = bytes32(WAD); 29 | ok = true; 30 | } 31 | 32 | /** 33 | @notice Return value 34 | @return val PRICE constant 35 | */ 36 | function read() external pure returns (bytes32 val) { 37 | val = bytes32(WAD); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/AllocatorRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | contract AllocatorRegistry { 20 | // --- storage variables --- 21 | 22 | mapping(address => uint256) public wards; 23 | mapping(bytes32 => address) public buffers; 24 | 25 | // --- events --- 26 | 27 | event Rely(address indexed usr); 28 | event Deny(address indexed usr); 29 | event File(bytes32 indexed ilk, bytes32 indexed what, address data); 30 | 31 | // --- modifiers --- 32 | 33 | modifier auth() { 34 | require(wards[msg.sender] == 1, "AllocatorRegistry/not-authorized"); 35 | _; 36 | } 37 | 38 | // --- constructor --- 39 | 40 | constructor() { 41 | wards[msg.sender] = 1; 42 | emit Rely(msg.sender); 43 | } 44 | 45 | // --- administration --- 46 | 47 | function rely(address usr) external auth { 48 | wards[usr] = 1; 49 | emit Rely(usr); 50 | } 51 | 52 | function deny(address usr) external auth { 53 | wards[usr] = 0; 54 | emit Deny(usr); 55 | } 56 | 57 | function file(bytes32 ilk, bytes32 what, address data) external auth { 58 | if (what == "buffer") { 59 | buffers[ilk] = data; 60 | } else revert("AllocatorRegistry/file-unrecognized-param"); 61 | emit File(ilk, what, data); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/AllocatorRoles.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2017 DappHub, LLC 2 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 3 | // SPDX-License-Identifier: AGPL-3.0-or-later 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | pragma solidity ^0.8.16; 19 | 20 | contract AllocatorRoles { 21 | // --- storage variables --- 22 | 23 | mapping(address => uint256) public wards; 24 | mapping(bytes32 => address) public ilkAdmins; 25 | mapping(bytes32 => mapping(address => bytes32)) public userRoles; 26 | mapping(bytes32 => mapping(address => mapping(bytes4 => bytes32))) public actionsRoles; 27 | 28 | // --- events --- 29 | 30 | event Rely(address indexed usr); 31 | event Deny(address indexed usr); 32 | event SetIlkAdmin(bytes32 indexed ilk, address user); 33 | event SetUserRole(bytes32 indexed ilk, address indexed who, uint8 indexed role, bool enabled); 34 | event SetRoleAction(bytes32 indexed ilk, uint8 indexed role, address indexed target, bytes4 sig, bool enabled); 35 | 36 | // --- modifiers --- 37 | 38 | modifier auth() { 39 | require(wards[msg.sender] == 1, "AllocatorRoles/not-authorized"); 40 | _; 41 | } 42 | 43 | modifier ilkAuth(bytes32 ilk) { 44 | require(ilkAdmins[ilk] == msg.sender, "AllocatorRoles/ilk-not-authorized"); 45 | _; 46 | } 47 | 48 | // --- constructor --- 49 | 50 | constructor() { 51 | wards[msg.sender] = 1; 52 | emit Rely(msg.sender); 53 | } 54 | 55 | // --- getters --- 56 | 57 | function hasUserRole(bytes32 ilk, address who, uint8 role) external view returns (bool has) { 58 | has = userRoles[ilk][who] & bytes32(uint256(1) << role) != bytes32(0); 59 | } 60 | 61 | function hasActionRole(bytes32 ilk, address target, bytes4 sig, uint8 role) external view returns (bool has) { 62 | has = actionsRoles[ilk][target][sig] & bytes32(uint256(1) << role) != bytes32(0); 63 | } 64 | 65 | // --- general administration --- 66 | 67 | function rely(address usr) external auth { 68 | wards[usr] = 1; 69 | emit Rely(usr); 70 | } 71 | 72 | function deny(address usr) external auth { 73 | wards[usr] = 0; 74 | emit Deny(usr); 75 | } 76 | 77 | function setIlkAdmin(bytes32 ilk, address usr) external auth { 78 | ilkAdmins[ilk] = usr; 79 | emit SetIlkAdmin(ilk, usr); 80 | } 81 | 82 | // --- ilk administration --- 83 | 84 | function setUserRole(bytes32 ilk, address who, uint8 role, bool enabled) public ilkAuth(ilk) { 85 | bytes32 mask = bytes32(uint256(1) << role); 86 | if (enabled) { 87 | userRoles[ilk][who] |= mask; 88 | } else { 89 | userRoles[ilk][who] &= ~mask; 90 | } 91 | emit SetUserRole(ilk, who, role, enabled); 92 | } 93 | 94 | function setRoleAction(bytes32 ilk, uint8 role, address target, bytes4 sig, bool enabled) external ilkAuth(ilk) { 95 | bytes32 mask = bytes32(uint256(1) << role); 96 | if (enabled) { 97 | actionsRoles[ilk][target][sig] |= mask; 98 | } else { 99 | actionsRoles[ilk][target][sig] &= ~mask; 100 | } 101 | emit SetRoleAction(ilk, role, target, sig, enabled); 102 | } 103 | 104 | // --- caller --- 105 | 106 | function canCall(bytes32 ilk, address caller, address target, bytes4 sig) external view returns (bool ok) { 107 | ok = userRoles[ilk][caller] & actionsRoles[ilk][target][sig] != bytes32(0); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/AllocatorVault.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2020 Lev Livnev 2 | // SPDX-FileCopyrightText: © 2021 Dai Foundation 3 | // SPDX-License-Identifier: AGPL-3.0-or-later 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Affero General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Affero General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Affero General Public License 16 | // along with this program. If not, see . 17 | 18 | pragma solidity ^0.8.16; 19 | 20 | interface RolesLike { 21 | function canCall(bytes32, address, address, bytes4) external view returns (bool); 22 | } 23 | 24 | interface VatLike { 25 | function frob(bytes32, address, address, address, int256, int256) external; 26 | function hope(address) external; 27 | } 28 | 29 | interface JugLike { 30 | function drip(bytes32) external returns (uint256); 31 | } 32 | 33 | interface GemLike { 34 | function approve(address, uint256) external; 35 | function transferFrom(address, address, uint256) external; 36 | } 37 | 38 | interface UsdsJoinLike { 39 | function usds() external view returns (GemLike); 40 | function vat() external view returns (VatLike); 41 | function exit(address, uint256) external; 42 | function join(address, uint256) external; 43 | } 44 | 45 | contract AllocatorVault { 46 | // --- storage variables --- 47 | 48 | mapping(address => uint256) public wards; 49 | JugLike public jug; 50 | 51 | // --- constants --- 52 | 53 | uint256 constant WAD = 10**18; 54 | uint256 constant RAY = 10**27; 55 | 56 | // --- immutables --- 57 | 58 | RolesLike immutable public roles; 59 | address immutable public buffer; 60 | VatLike immutable public vat; 61 | bytes32 immutable public ilk; 62 | UsdsJoinLike immutable public usdsJoin; 63 | GemLike immutable public usds; 64 | 65 | // --- events --- 66 | 67 | event Rely(address indexed usr); 68 | event Deny(address indexed usr); 69 | event File(bytes32 indexed what, address data); 70 | event Draw(address indexed sender, uint256 wad); 71 | event Wipe(address indexed sender, uint256 wad); 72 | 73 | // --- modifiers --- 74 | 75 | modifier auth() { 76 | require(roles.canCall(ilk, msg.sender, address(this), msg.sig) || 77 | wards[msg.sender] == 1, "AllocatorVault/not-authorized"); 78 | _; 79 | } 80 | 81 | // --- constructor --- 82 | 83 | constructor(address roles_, address buffer_, bytes32 ilk_, address usdsJoin_) { 84 | roles = RolesLike(roles_); 85 | 86 | buffer = buffer_; 87 | ilk = ilk_; 88 | usdsJoin = UsdsJoinLike(usdsJoin_); 89 | 90 | vat = usdsJoin.vat(); 91 | usds = usdsJoin.usds(); 92 | 93 | vat.hope(usdsJoin_); 94 | usds.approve(usdsJoin_, type(uint256).max); 95 | 96 | wards[msg.sender] = 1; 97 | emit Rely(msg.sender); 98 | } 99 | 100 | // --- math --- 101 | 102 | function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) { 103 | // Note: _divup(0,0) will return 0 differing from natural solidity division 104 | unchecked { 105 | z = x != 0 ? ((x - 1) / y) + 1 : 0; 106 | } 107 | } 108 | 109 | // --- administration --- 110 | 111 | function rely(address usr) external auth { 112 | wards[usr] = 1; 113 | emit Rely(usr); 114 | } 115 | 116 | function deny(address usr) external auth { 117 | wards[usr] = 0; 118 | emit Deny(usr); 119 | } 120 | 121 | function file(bytes32 what, address data) external auth { 122 | if (what == "jug") { 123 | jug = JugLike(data); 124 | } else revert("AllocatorVault/file-unrecognized-param"); 125 | emit File(what, data); 126 | } 127 | 128 | // --- funnels execution --- 129 | 130 | function draw(uint256 wad) external auth { 131 | uint256 rate = jug.drip(ilk); 132 | uint256 dart = _divup(wad * RAY, rate); 133 | require(dart <= uint256(type(int256).max), "AllocatorVault/overflow"); 134 | vat.frob(ilk, address(this), address(0), address(this), 0, int256(dart)); 135 | usdsJoin.exit(buffer, wad); 136 | emit Draw(msg.sender, wad); 137 | } 138 | 139 | function wipe(uint256 wad) external auth { 140 | usds.transferFrom(buffer, address(this), wad); 141 | usdsJoin.join(address(this), wad); 142 | uint256 rate = jug.drip(ilk); 143 | uint256 dart = wad * RAY / rate; 144 | require(dart <= uint256(type(int256).max), "AllocatorVault/overflow"); 145 | vat.frob(ilk, address(this), address(0), address(this), 0, -int256(dart)); 146 | emit Wipe(msg.sender, wad); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/IAllocatorConduit.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity >=0.8.0; 18 | 19 | /** 20 | * @title IAllocatorConduit 21 | * @dev Conduits are to be used to manage investment positions for multiple Allocators. 22 | */ 23 | interface IAllocatorConduit { 24 | /** 25 | * @dev Event emitted when a deposit is made to the Conduit. 26 | * @param ilk The unique identifier of the ilk. 27 | * @param asset The address of the asset deposited. 28 | * @param origin The address where the asset is coming from. 29 | * @param amount The amount of asset deposited. 30 | */ 31 | event Deposit(bytes32 indexed ilk, address indexed asset, address origin, uint256 amount); 32 | 33 | /** 34 | * @dev Event emitted when a withdrawal is made from the Conduit. 35 | * @param ilk The unique identifier of the ilk. 36 | * @param asset The address of the asset withdrawn. 37 | * @param destination The address where the asset is sent. 38 | * @param amount The amount of asset withdrawn. 39 | */ 40 | event Withdraw(bytes32 indexed ilk, address indexed asset, address destination, uint256 amount); 41 | 42 | /** 43 | * @dev Function for depositing tokens into a Fund Manager. 44 | * @param ilk The unique identifier of the ilk. 45 | * @param asset The asset to deposit. 46 | * @param amount The amount of tokens to deposit. 47 | */ 48 | function deposit(bytes32 ilk, address asset, uint256 amount) external; 49 | 50 | /** 51 | * @dev Function for withdrawing tokens from a Fund Manager. 52 | * @param ilk The unique identifier of the ilk. 53 | * @param asset The asset to withdraw. 54 | * @param maxAmount The max amount of tokens to withdraw. Setting to "type(uint256).max" will ensure to withdraw all available liquidity. 55 | * @return amount The amount of tokens withdrawn. 56 | */ 57 | function withdraw(bytes32 ilk, address asset, uint256 maxAmount) external returns (uint256 amount); 58 | 59 | /** 60 | * @dev Function to get the maximum deposit possible for a specific asset and ilk. 61 | * @param ilk The unique identifier of the ilk. 62 | * @param asset The asset to check. 63 | * @return maxDeposit_ The maximum possible deposit for the asset. 64 | */ 65 | function maxDeposit(bytes32 ilk, address asset) external view returns (uint256 maxDeposit_); 66 | 67 | /** 68 | * @dev Function to get the maximum withdrawal possible for a specific asset and ilk. 69 | * @param ilk The unique identifier of the ilk. 70 | * @param asset The asset to check. 71 | * @return maxWithdraw_ The maximum possible withdrawal for the asset. 72 | */ 73 | function maxWithdraw(bytes32 ilk, address asset) external view returns (uint256 maxWithdraw_); 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/funnels/Swapper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface RolesLike { 20 | function canCall(bytes32, address, address, bytes4) external view returns (bool); 21 | } 22 | 23 | interface GemLike { 24 | function balanceOf(address) external view returns (uint256); 25 | function transfer(address, uint256) external; 26 | function transferFrom(address, address, uint256) external; 27 | } 28 | 29 | interface CalleeLike { 30 | function swapCallback(address, address, uint256, uint256, address, bytes calldata) external; 31 | } 32 | 33 | contract Swapper { 34 | mapping (address => uint256) public wards; // Admins 35 | mapping (address => mapping (address => PairLimit)) public limits; // Rate limit parameters per src->dst pair 36 | 37 | RolesLike public immutable roles; // Contract managing access control for this Swapper 38 | bytes32 public immutable ilk; // Collateral type 39 | address public immutable buffer; // Contract from which the GEM to sell is pulled and to which the bought GEM is pushed 40 | 41 | struct PairLimit { 42 | uint96 cap; // Maximum amount of src token that can be swapped each era for a src->dst pair 43 | uint32 era; // Cooldown period it has to wait for renewing the due amount to cap for src to dst swap 44 | uint96 due; // Pending amount of src token that can still be swapped until next era 45 | uint32 end; // Timestamp of when the current batch ends 46 | } 47 | 48 | event Rely(address indexed usr); 49 | event Deny(address indexed usr); 50 | event SetLimits(address indexed src, address indexed dst, uint96 cap, uint32 era); 51 | event Swap(address indexed sender, address indexed src, address indexed dst, uint256 amt, uint256 out); 52 | 53 | constructor(address roles_, bytes32 ilk_, address buffer_) { 54 | roles = RolesLike(roles_); 55 | ilk = ilk_; 56 | buffer = buffer_; 57 | wards[msg.sender] = 1; 58 | emit Rely(msg.sender); 59 | } 60 | 61 | modifier auth() { 62 | require(roles.canCall(ilk, msg.sender, address(this), msg.sig) || wards[msg.sender] == 1, "Swapper/not-authorized"); 63 | _; 64 | } 65 | 66 | function rely(address usr) external auth { 67 | wards[usr] = 1; 68 | emit Rely(usr); 69 | } 70 | 71 | function deny(address usr) external auth { 72 | wards[usr] = 0; 73 | emit Deny(usr); 74 | } 75 | 76 | function setLimits(address src, address dst, uint96 cap, uint32 era) external auth { 77 | limits[src][dst] = PairLimit({ 78 | cap: cap, 79 | era: era, 80 | due: 0, 81 | end: 0 82 | }); 83 | emit SetLimits(src, dst, cap, era); 84 | } 85 | 86 | function swap(address src, address dst, uint256 amt, uint256 minOut, address callee, bytes calldata data) external auth returns (uint256 out) { 87 | PairLimit memory limit = limits[src][dst]; 88 | 89 | if (block.timestamp >= limit.end) { 90 | // Reset batch 91 | limit.due = limit.cap; 92 | limit.end = uint32(block.timestamp) + limit.era; 93 | } 94 | 95 | require(amt <= limit.due, "Swapper/exceeds-due-amt"); 96 | 97 | unchecked { 98 | limits[src][dst].due = limit.due - uint96(amt); 99 | limits[src][dst].end = limit.end; 100 | } 101 | 102 | GemLike(src).transferFrom(buffer, callee, amt); 103 | 104 | // Avoid swapping directly to buffer to prevent piggybacking another operation to satisfy the balance check 105 | CalleeLike(callee).swapCallback(src, dst, amt, minOut, address(this), data); 106 | 107 | out = GemLike(dst).balanceOf(address(this)); 108 | require(out >= minOut, "Swapper/too-few-dst-received"); 109 | 110 | GemLike(dst).transfer(buffer, out); 111 | emit Swap(msg.sender, src, dst, amt, out); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/funnels/automation/ConduitMover.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface ConduitLike { 20 | function deposit(bytes32, address, uint256) external; 21 | function withdraw(bytes32, address, uint256) external returns (uint256); 22 | } 23 | 24 | contract ConduitMover { 25 | mapping (address => uint256) public wards; // Admins 26 | mapping (address => uint256) public buds; // Whitelisted keepers 27 | mapping (address => mapping (address => mapping (address => MoveConfig))) public configs; // Configuration for keepers 28 | 29 | bytes32 public immutable ilk; // Collateral type 30 | address public immutable buffer; // The address of the buffer contract 31 | 32 | struct MoveConfig { 33 | uint64 num; // The remaining number of times that a `from` to `to` gem move can be performed by keepers 34 | uint32 hop; // Cooldown period it has to wait between `from` to `to` gem moves 35 | uint32 zzz; // Timestamp of the last `from` to `to` gem move 36 | uint128 lot; // The amount to move every hop for a `from` to `to` gem move 37 | } 38 | 39 | event Rely(address indexed usr); 40 | event Deny(address indexed usr); 41 | event Kiss(address indexed usr); 42 | event Diss(address indexed usr); 43 | event SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot); 44 | event Move(address indexed from, address indexed to, address indexed gem, uint128 lot); 45 | 46 | constructor(bytes32 ilk_, address buffer_) { 47 | buffer = buffer_; 48 | ilk = ilk_; 49 | 50 | wards[msg.sender] = 1; 51 | emit Rely(msg.sender); 52 | } 53 | 54 | modifier auth { 55 | require(wards[msg.sender] == 1, "ConduitMover/not-authorized"); 56 | _; 57 | } 58 | 59 | modifier toll { 60 | require(buds[msg.sender] == 1, "ConduitMover/non-keeper"); 61 | _; 62 | } 63 | 64 | function rely(address usr) external auth { 65 | wards[usr] = 1; 66 | emit Rely(usr); 67 | } 68 | 69 | function deny(address usr) external auth { 70 | wards[usr] = 0; 71 | emit Deny(usr); 72 | } 73 | 74 | function kiss(address usr) external auth { 75 | buds[usr] = 1; 76 | emit Kiss(usr); 77 | } 78 | 79 | function diss(address usr) external auth { 80 | buds[usr] = 0; 81 | emit Diss(usr); 82 | } 83 | 84 | function setConfig(address from, address to, address gem, uint64 num, uint32 hop, uint128 lot) external auth { 85 | configs[from][to][gem] = MoveConfig({ 86 | num: num, 87 | hop: hop, 88 | zzz: 0, 89 | lot: lot 90 | }); 91 | emit SetConfig(from, to, gem, num, hop, lot); 92 | } 93 | 94 | function move(address from, address to, address gem) toll external { 95 | MoveConfig memory cfg = configs[from][to][gem]; 96 | 97 | require(cfg.num > 0, "ConduitMover/exceeds-num"); 98 | require(block.timestamp >= cfg.zzz + cfg.hop, "ConduitMover/too-soon"); 99 | unchecked { configs[from][to][gem].num = cfg.num - 1; } 100 | configs[from][to][gem].zzz = uint32(block.timestamp); 101 | 102 | if (from != buffer) { 103 | require(ConduitLike(from).withdraw(ilk, gem, cfg.lot) == cfg.lot, "ConduitMover/lot-withdraw-failed"); 104 | } 105 | if (to != buffer) { 106 | ConduitLike(to).deposit(ilk, gem, cfg.lot); 107 | } 108 | 109 | emit Move(from, to, gem, cfg.lot); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/funnels/automation/StableDepositorUniV3.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface DepositorUniV3Like { 20 | struct LiquidityParams { 21 | address gem0; 22 | address gem1; 23 | uint24 fee; 24 | int24 tickLower; 25 | int24 tickUpper; 26 | uint128 liquidity; 27 | uint256 amt0Desired; // Relevant only if liquidity == 0 28 | uint256 amt1Desired; // Relevant only if liquidity == 0 29 | uint256 amt0Min; 30 | uint256 amt1Min; 31 | } 32 | 33 | function deposit(LiquidityParams memory params) external returns ( 34 | uint128 liquidity, 35 | uint256 amt0, 36 | uint256 amt1 37 | ); 38 | 39 | function withdraw(LiquidityParams memory p, bool takeFee) external returns ( 40 | uint128 liquidity, 41 | uint256 amt0, 42 | uint256 amt1, 43 | uint256 fees0, 44 | uint256 fees1 45 | ); 46 | 47 | struct CollectParams { 48 | address gem0; 49 | address gem1; 50 | uint24 fee; 51 | int24 tickLower; 52 | int24 tickUpper; 53 | } 54 | 55 | function collect(CollectParams memory p) external returns ( 56 | uint256 fees0, 57 | uint256 fees1 58 | ); 59 | } 60 | 61 | contract StableDepositorUniV3 { 62 | mapping (address => uint256) public wards; // Admins 63 | mapping (address => uint256) public buds; // Whitelisted keepers 64 | mapping (address => mapping (address => mapping (uint24 => mapping (int24 => mapping (int24 => PairConfig))))) public configs; // Configuration for keepers 65 | 66 | DepositorUniV3Like public immutable depositor; // DepositorUniV3 for this StableDepositorUniV3 67 | 68 | struct PairConfig { 69 | int32 num; // The remaining number of times that a (gem0, gem1) operation can be performed by keepers (> 0: deposit, < 0: withdraw) 70 | uint32 zzz; // Timestamp of the last deposit/withdraw execution 71 | uint96 amt0; // Amount of gem0 to deposit/withdraw each (gem0, gem1) operation 72 | uint96 amt1; // Amount of gem1 to deposit/withdraw each (gem0, gem1) operation 73 | uint96 req0; // The minimum required deposit/withdraw amount of gem0 to insist on in each (gem0, gem1) operation 74 | uint96 req1; // The minimum required deposit/withdraw amount of gem1 to insist on in each (gem0, gem1) operation 75 | uint32 hop; // Cooldown period it has to wait between deposit/withdraw executions 76 | } 77 | 78 | event Rely(address indexed usr); 79 | event Deny(address indexed usr); 80 | event Kiss(address indexed usr); 81 | event Diss(address indexed usr); 82 | event SetConfig(address indexed gem0, address indexed gem1, uint24 indexed fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1); 83 | 84 | constructor(address _depositor) { 85 | depositor = DepositorUniV3Like(_depositor); 86 | 87 | wards[msg.sender] = 1; 88 | emit Rely(msg.sender); 89 | } 90 | 91 | modifier auth { 92 | require(wards[msg.sender] == 1, "StableDepositorUniV3/not-authorized"); 93 | _; 94 | } 95 | 96 | // Permissionned to whitelisted keepers 97 | modifier toll { 98 | require(buds[msg.sender] == 1, "StableDepositorUniV3/non-keeper"); 99 | _; 100 | } 101 | 102 | function rely(address usr) external auth { 103 | wards[usr] = 1; 104 | emit Rely(usr); 105 | } 106 | 107 | function deny(address usr) external auth { 108 | wards[usr] = 0; 109 | emit Deny(usr); 110 | } 111 | 112 | function kiss(address usr) external auth { 113 | buds[usr] = 1; 114 | emit Kiss(usr); 115 | } 116 | 117 | function diss(address usr) external auth { 118 | buds[usr] = 0; 119 | emit Diss(usr); 120 | } 121 | 122 | function setConfig(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, int32 num, uint32 hop, uint96 amt0, uint96 amt1, uint96 req0, uint96 req1) external auth { 123 | require(gem0 < gem1, "StableDepositorUniV3/wrong-gem-order"); 124 | configs[gem0][gem1][fee][tickLower][tickUpper] = PairConfig({ 125 | num: num, 126 | zzz: 0, 127 | amt0: amt0, 128 | amt1: amt1, 129 | req0: req0, 130 | req1: req1, 131 | hop: hop 132 | }); 133 | emit SetConfig(gem0, gem1, fee, tickLower, tickUpper, num, hop, amt0, amt1, req0, req1); 134 | } 135 | 136 | // Note: the keeper's minAmts value must be updated whenever configs[gem0][gem1][fee][tickLower][tickUpper] is changed. 137 | // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[gem0][gem1][fee][tickLower][tickUpper].req0/1). 138 | function deposit(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) 139 | toll 140 | external 141 | returns (uint128 liquidity, uint256 amt0, uint256 amt1) 142 | { 143 | PairConfig memory cfg = configs[gem0][gem1][fee][tickLower][tickUpper]; 144 | 145 | require(cfg.num > 0, "StableDepositorUniV3/exceeds-num"); 146 | require(block.timestamp >= cfg.zzz + cfg.hop, "StableDepositorUniV3/too-soon"); 147 | unchecked { configs[gem0][gem1][fee][tickLower][tickUpper].num = cfg.num - 1; } 148 | configs[gem0][gem1][fee][tickLower][tickUpper].zzz = uint32(block.timestamp); 149 | 150 | if (amt0Min == 0) amt0Min = cfg.req0; 151 | if (amt1Min == 0) amt1Min = cfg.req1; 152 | require(amt0Min >= cfg.req0, "StableDepositorUniV3/min-amt0-too-small"); 153 | require(amt1Min >= cfg.req1, "StableDepositorUniV3/min-amt1-too-small"); 154 | 155 | DepositorUniV3Like.LiquidityParams memory p = DepositorUniV3Like.LiquidityParams({ 156 | gem0 : gem0, 157 | gem1 : gem1, 158 | fee : fee, 159 | tickLower : tickLower, 160 | tickUpper : tickUpper, 161 | liquidity : 0, // Use desired amounts 162 | amt0Desired: cfg.amt0, 163 | amt1Desired: cfg.amt1, 164 | amt0Min : amt0Min, 165 | amt1Min : amt1Min 166 | }); 167 | (liquidity, amt0, amt1) = depositor.deposit(p); 168 | } 169 | 170 | // Note: the keeper's minAmts value must be updated whenever configs[gem0][gem1][fee][tickLower][tickUpper] is changed. 171 | // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[gem0][gem1][fee][tickLower][tickUpper].req0/1). 172 | function withdraw(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 amt0Min, uint128 amt1Min) 173 | toll 174 | external 175 | returns (uint128 liquidity, uint256 amt0, uint256 amt1, uint256 fees0, uint256 fees1) 176 | { 177 | PairConfig memory cfg = configs[gem0][gem1][fee][tickLower][tickUpper]; 178 | 179 | require(cfg.num < 0, "StableDepositorUniV3/exceeds-num"); 180 | require(block.timestamp >= cfg.zzz + cfg.hop, "StableDepositorUniV3/too-soon"); 181 | unchecked { configs[gem0][gem1][fee][tickLower][tickUpper].num = cfg.num + 1; } 182 | configs[gem0][gem1][fee][tickLower][tickUpper].zzz = uint32(block.timestamp); 183 | 184 | if (amt0Min == 0) amt0Min = cfg.req0; 185 | if (amt1Min == 0) amt1Min = cfg.req1; 186 | require(amt0Min >= cfg.req0, "StableDepositorUniV3/min-amt0-too-small"); 187 | require(amt1Min >= cfg.req1, "StableDepositorUniV3/min-amt1-too-small"); 188 | 189 | DepositorUniV3Like.LiquidityParams memory p = DepositorUniV3Like.LiquidityParams({ 190 | gem0 : gem0, 191 | gem1 : gem1, 192 | fee : fee, 193 | tickLower : tickLower, 194 | tickUpper : tickUpper, 195 | liquidity : 0, // Use desired amounts 196 | amt0Desired: cfg.amt0, 197 | amt1Desired: cfg.amt1, 198 | amt0Min : amt0Min, 199 | amt1Min : amt1Min 200 | }); 201 | (liquidity, amt0, amt1, fees0, fees1) = depositor.withdraw(p, true); 202 | } 203 | 204 | function collect(address gem0, address gem1, uint24 fee, int24 tickLower, int24 tickUpper) 205 | toll 206 | external 207 | returns (uint256 fees0, uint256 fees1) 208 | { 209 | DepositorUniV3Like.CollectParams memory collectParams = DepositorUniV3Like.CollectParams({ 210 | gem0 : gem0, 211 | gem1 : gem1, 212 | fee : fee, 213 | tickLower: tickLower, 214 | tickUpper: tickUpper 215 | }); 216 | (fees0, fees1) = depositor.collect(collectParams); 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /src/funnels/automation/StableSwapper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface SwapperLike { 20 | function swap(address, address, uint256, uint256, address, bytes calldata) external returns (uint256); 21 | } 22 | 23 | contract StableSwapper { 24 | mapping (address => uint256) public wards; // Admins 25 | mapping (address => uint256) public buds; // Whitelisted keepers 26 | mapping (address => mapping (address => PairConfig)) public configs; // Configuration for keepers 27 | 28 | SwapperLike public immutable swapper; // Swapper for this StableSwapper 29 | 30 | struct PairConfig { 31 | uint128 num; // The remaining number of times that a src to dst swap can be performed by keepers 32 | uint32 hop; // Cooldown period it has to wait between swap executions 33 | uint32 zzz; // Timestamp of the last swap execution 34 | uint96 lot; // The amount swapped by keepers from src to dst every hop 35 | uint96 req; // The minimum required output amount to insist on in the swap from src to dst 36 | } 37 | 38 | event Rely(address indexed usr); 39 | event Deny(address indexed usr); 40 | event Kiss(address indexed usr); 41 | event Diss(address indexed usr); 42 | event SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req); 43 | 44 | constructor(address swapper_) { 45 | swapper = SwapperLike(swapper_); 46 | wards[msg.sender] = 1; 47 | emit Rely(msg.sender); 48 | } 49 | 50 | modifier auth { 51 | require(wards[msg.sender] == 1, "StableSwapper/not-authorized"); 52 | _; 53 | } 54 | 55 | // permissioned to whitelisted keepers 56 | modifier toll { 57 | require(buds[msg.sender] == 1, "StableSwapper/non-keeper"); 58 | _; 59 | } 60 | 61 | function rely(address usr) external auth { 62 | wards[usr] = 1; 63 | emit Rely(usr); 64 | } 65 | 66 | function deny(address usr) external auth { 67 | wards[usr] = 0; 68 | emit Deny(usr); 69 | } 70 | 71 | function kiss(address usr) external auth { 72 | buds[usr] = 1; 73 | emit Kiss(usr); 74 | } 75 | 76 | function diss(address usr) external auth { 77 | buds[usr] = 0; 78 | emit Diss(usr); 79 | } 80 | 81 | function setConfig(address src, address dst, uint128 num, uint32 hop, uint96 lot, uint96 req) external auth { 82 | configs[src][dst] = PairConfig({ 83 | num: num, 84 | hop: hop, 85 | zzz: 0, 86 | lot: lot, 87 | req: req 88 | }); 89 | emit SetConfig(src, dst, num, hop, lot, req); 90 | } 91 | 92 | // Note: the keeper's minOut value must be updated whenever configs[src][dst] is changed. 93 | // Failing to do so may result in this call reverting or in taking on more slippage than intended (up to a limit controlled by configs[src][dst].min). 94 | function swap(address src, address dst, uint256 minOut, address callee, bytes calldata data) toll external returns (uint256 out) { 95 | PairConfig memory cfg = configs[src][dst]; 96 | 97 | require(cfg.num > 0, "StableSwapper/exceeds-num"); 98 | require(block.timestamp >= cfg.zzz + cfg.hop, "StableSwapper/too-soon"); 99 | unchecked { configs[src][dst].num = cfg.num - 1; } 100 | configs[src][dst].zzz = uint32(block.timestamp); 101 | 102 | if (minOut == 0) minOut = cfg.req; 103 | require(minOut >= cfg.req, "StableSwapper/min-too-small"); 104 | 105 | out = swapper.swap(src, dst, cfg.lot, minOut, callee, data); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/funnels/automation/VaultMinter.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface AllocatorVaultLike { 20 | function draw(uint256) external; 21 | function wipe(uint256) external; 22 | } 23 | 24 | contract VaultMinter { 25 | mapping (address => uint256) public wards; // Admins 26 | mapping (address => uint256) public buds; // Whitelisted keepers 27 | MinterConfig public config; // Configuration for keepers 28 | 29 | address public immutable vault; // The address of the vault contract 30 | 31 | struct MinterConfig { 32 | int64 num; // The remaining number of times that a draw or wipe can be executed by keepers (> 0: draw, < 0: wipe) 33 | uint32 hop; // Cooldown period it has to wait between each action 34 | uint32 zzz; // Timestamp of the last action 35 | uint128 lot; // The amount to draw or wipe every hop 36 | } 37 | 38 | event Rely(address indexed usr); 39 | event Deny(address indexed usr); 40 | event Kiss(address indexed usr); 41 | event Diss(address indexed usr); 42 | event SetConfig(int64 num, uint32 hop, uint128 lot); 43 | event Draw(uint128 lot); 44 | event Wipe(uint128 lot); 45 | 46 | constructor(address vault_) { 47 | vault = vault_; 48 | 49 | wards[msg.sender] = 1; 50 | emit Rely(msg.sender); 51 | } 52 | 53 | modifier auth { 54 | require(wards[msg.sender] == 1, "VaultMinter/not-authorized"); 55 | _; 56 | } 57 | 58 | modifier toll { 59 | require(buds[msg.sender] == 1, "VaultMinter/non-keeper"); 60 | _; 61 | } 62 | 63 | function rely(address usr) external auth { 64 | wards[usr] = 1; 65 | emit Rely(usr); 66 | } 67 | 68 | function deny(address usr) external auth { 69 | wards[usr] = 0; 70 | emit Deny(usr); 71 | } 72 | 73 | function kiss(address usr) external auth { 74 | buds[usr] = 1; 75 | emit Kiss(usr); 76 | } 77 | 78 | function diss(address usr) external auth { 79 | buds[usr] = 0; 80 | emit Diss(usr); 81 | } 82 | 83 | function setConfig(int64 num, uint32 hop, uint128 lot) external auth { 84 | config = MinterConfig({ 85 | num: num, 86 | hop: hop, 87 | zzz: 0, 88 | lot: lot 89 | }); 90 | emit SetConfig(num, hop, lot); 91 | } 92 | 93 | function draw() toll external { 94 | MinterConfig memory cfg = config; 95 | 96 | require(cfg.num > 0, "VaultMinter/exceeds-num"); 97 | require(block.timestamp >= cfg.zzz + cfg.hop, "VaultMinter/too-soon"); 98 | unchecked { config.num = cfg.num - 1; } 99 | config.zzz = uint32(block.timestamp); 100 | 101 | AllocatorVaultLike(vault).draw(cfg.lot); 102 | 103 | emit Draw(cfg.lot); 104 | } 105 | 106 | function wipe() toll external { 107 | MinterConfig memory cfg = config; 108 | 109 | require(cfg.num < 0, "VaultMinter/exceeds-num"); 110 | require(block.timestamp >= cfg.zzz + cfg.hop, "VaultMinter/too-soon"); 111 | unchecked { config.num = cfg.num + 1; } 112 | config.zzz = uint32(block.timestamp); 113 | 114 | AllocatorVaultLike(vault).wipe(cfg.lot); 115 | 116 | emit Wipe(cfg.lot); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/funnels/callees/SwapperCalleePsm.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface GemLike { 20 | function approve(address, uint256) external; 21 | function decimals() external view returns (uint8); 22 | } 23 | 24 | interface PsmLike { 25 | function sellGemNoFee(address, uint256) external returns (uint256); 26 | function buyGemNoFee(address, uint256) external returns (uint256); 27 | function dai() external returns (address); 28 | function gem() external returns (address); 29 | } 30 | 31 | contract SwapperCalleePsm { 32 | mapping (address => uint256) public wards; 33 | 34 | address public immutable psm; 35 | address public immutable gem; 36 | uint256 public immutable to18ConversionFactor; 37 | 38 | event Rely(address indexed usr); 39 | event Deny(address indexed usr); 40 | 41 | constructor(address _psm) { 42 | psm = _psm; 43 | gem = PsmLike(psm).gem(); 44 | GemLike(PsmLike(psm).dai()).approve(address(psm), type(uint256).max); 45 | GemLike(gem).approve(address(psm), type(uint256).max); 46 | to18ConversionFactor = 10 ** (18 - GemLike(gem).decimals()); 47 | 48 | wards[msg.sender] = 1; 49 | emit Rely(msg.sender); 50 | } 51 | 52 | modifier auth() { 53 | require(wards[msg.sender] == 1, "SwapperCalleePsm/not-authorized"); 54 | _; 55 | } 56 | 57 | function rely(address usr) external auth { 58 | wards[usr] = 1; 59 | emit Rely(usr); 60 | } 61 | 62 | function deny(address usr) external auth { 63 | wards[usr] = 0; 64 | emit Deny(usr); 65 | } 66 | 67 | // Note: To avoid accumulating dust in this contract, `amt` should be a multiple of `to18ConversionFactor` when `src != gem`. 68 | // This constraint is intentionally not enforced in this contract. 69 | function swapCallback(address src, address /* dst */, uint256 amt, uint256 /* minOut */, address to, bytes calldata /* data */) external auth { 70 | if (src == gem) PsmLike(psm).sellGemNoFee(to, amt); 71 | else PsmLike(psm).buyGemNoFee (to, amt / to18ConversionFactor); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/funnels/callees/SwapperCalleeUniV3.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | interface GemLike { 20 | function approve(address, uint256) external; 21 | } 22 | 23 | // https://github.com/Uniswap/v3-periphery/blob/b06959dd01f5999aa93e1dc530fe573c7bb295f6/contracts/SwapRouter.sol 24 | interface SwapRouterLike { 25 | function exactInput(ExactInputParams calldata params) external returns (uint256 amountOut); 26 | 27 | // https://github.com/Uniswap/v3-periphery/blob/b06959dd01f5999aa93e1dc530fe573c7bb295f6/contracts/interfaces/ISwapRouter.sol#L26 28 | // https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps#input-parameters 29 | struct ExactInputParams { 30 | bytes path; 31 | address recipient; 32 | uint256 deadline; 33 | uint256 amountIn; 34 | uint256 amountOutMinimum; 35 | } 36 | } 37 | 38 | contract SwapperCalleeUniV3 { 39 | address public immutable uniV3Router; 40 | 41 | constructor(address _uniV3Router) { 42 | uniV3Router = _uniV3Router; 43 | } 44 | 45 | function swapCallback(address src, address /* dst */, uint256 amt, uint256 minOut, address to, bytes calldata data) external { 46 | bytes memory path = data; 47 | 48 | address src_; 49 | assembly { 50 | src_ := shr(0x60, mload(add(path, 0x20))) 51 | } 52 | require(src == src_, "SwapperCalleeUniV3/invalid-path"); // forbids lingering approval of src 53 | 54 | GemLike(src).approve(uniV3Router, amt); 55 | SwapRouterLike.ExactInputParams memory params = SwapRouterLike.ExactInputParams({ 56 | path: path, 57 | recipient: to, 58 | deadline: block.timestamp, 59 | amountIn: amt, 60 | amountOutMinimum: minOut 61 | }); 62 | SwapRouterLike(uniV3Router).exactInput(params); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/funnels/uniV3/FullMath.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0 2 | 3 | // Based on https://github.com/gelatodigital/g-uni-v1-core/blob/bea63422e2155242b051896b635508b7a99d2a1a/contracts/vendor/uniswap/FullMath.sol 4 | // Uniswap version - https://github.com/Uniswap/v3-core/blob/412d9b236a1e75a98568d49b1aeb21e3a1430544/contracts/libraries/FullMath.sol 5 | 6 | pragma solidity ^0.8.16; 7 | 8 | /// @title Contains 512-bit math functions 9 | /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision 10 | /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits 11 | library FullMath { 12 | /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 13 | /// @param a The multiplicand 14 | /// @param b The multiplier 15 | /// @param denominator The divisor 16 | /// @return result The 256-bit result 17 | /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv 18 | function mulDiv( 19 | uint256 a, 20 | uint256 b, 21 | uint256 denominator 22 | ) internal pure returns (uint256 result) { 23 | unchecked { 24 | // 512-bit multiply [prod1 prod0] = a * b 25 | // Compute the product mod 2**256 and mod 2**256 - 1 26 | // then use the Chinese Remainder Theorem to reconstruct 27 | // the 512 bit result. The result is stored in two 256 28 | // variables such that product = prod1 * 2**256 + prod0 29 | uint256 prod0; // Least significant 256 bits of the product 30 | uint256 prod1; // Most significant 256 bits of the product 31 | assembly { 32 | let mm := mulmod(a, b, not(0)) 33 | prod0 := mul(a, b) 34 | prod1 := sub(sub(mm, prod0), lt(mm, prod0)) 35 | } 36 | 37 | // Handle non-overflow cases, 256 by 256 division 38 | if (prod1 == 0) { 39 | require(denominator > 0); 40 | assembly { 41 | result := div(prod0, denominator) 42 | } 43 | return result; 44 | } 45 | 46 | // Make sure the result is less than 2**256. 47 | // Also prevents denominator == 0 48 | require(denominator > prod1); 49 | 50 | /////////////////////////////////////////////// 51 | // 512 by 256 division. 52 | /////////////////////////////////////////////// 53 | 54 | // Make division exact by subtracting the remainder from [prod1 prod0] 55 | // Compute remainder using mulmod 56 | uint256 remainder; 57 | assembly { 58 | remainder := mulmod(a, b, denominator) 59 | } 60 | // Subtract 256 bit number from 512 bit number 61 | assembly { 62 | prod1 := sub(prod1, gt(remainder, prod0)) 63 | prod0 := sub(prod0, remainder) 64 | } 65 | 66 | // Factor powers of two out of denominator 67 | // Compute largest power of two divisor of denominator. 68 | // Always >= 1. 69 | // EDIT for 0.8 compatibility: 70 | // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256 71 | uint256 twos = denominator & (~denominator + 1); 72 | 73 | // Divide denominator by power of two 74 | assembly { 75 | denominator := div(denominator, twos) 76 | } 77 | 78 | // Divide [prod1 prod0] by the factors of two 79 | assembly { 80 | prod0 := div(prod0, twos) 81 | } 82 | // Shift in bits from prod1 into prod0. For this we need 83 | // to flip `twos` such that it is 2**256 / twos. 84 | // If twos is zero, then it becomes one 85 | assembly { 86 | twos := add(div(sub(0, twos), twos), 1) 87 | } 88 | prod0 |= prod1 * twos; 89 | 90 | // Invert denominator mod 2**256 91 | // Now that denominator is an odd number, it has an inverse 92 | // modulo 2**256 such that denominator * inv = 1 mod 2**256. 93 | // Compute the inverse by starting with a seed that is correct 94 | // correct for four bits. That is, denominator * inv = 1 mod 2**4 95 | uint256 inv = (3 * denominator) ^ 2; 96 | // Now use Newton-Raphson iteration to improve the precision. 97 | // Thanks to Hensel's lifting lemma, this also works in modular 98 | // arithmetic, doubling the correct bits in each step. 99 | inv *= 2 - denominator * inv; // inverse mod 2**8 100 | inv *= 2 - denominator * inv; // inverse mod 2**16 101 | inv *= 2 - denominator * inv; // inverse mod 2**32 102 | inv *= 2 - denominator * inv; // inverse mod 2**64 103 | inv *= 2 - denominator * inv; // inverse mod 2**128 104 | inv *= 2 - denominator * inv; // inverse mod 2**256 105 | 106 | // Because the division is now exact we can divide by multiplying 107 | // with the modular inverse of denominator. This will give us the 108 | // correct result modulo 2**256. Since the precoditions guarantee 109 | // that the outcome is less than 2**256, this is the final result. 110 | // We don't need to compute the high bits of the result and prod1 111 | // is no longer required. 112 | result = prod0 * inv; 113 | return result; 114 | } 115 | } 116 | 117 | /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 118 | /// @param a The multiplicand 119 | /// @param b The multiplier 120 | /// @param denominator The divisor 121 | /// @return result The 256-bit result 122 | function mulDivRoundingUp( 123 | uint256 a, 124 | uint256 b, 125 | uint256 denominator 126 | ) internal pure returns (uint256 result) { 127 | result = mulDiv(a, b, denominator); 128 | if (mulmod(a, b, denominator) > 0) { 129 | require(result < type(uint256).max); 130 | result++; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/funnels/uniV3/LiquidityAmounts.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | 3 | // Based on https://github.com/Uniswap/v3-periphery/blob/6cce88e63e176af1ddb6cc56e029110289622317/contracts/libraries/LiquidityAmounts.sol 4 | 5 | pragma solidity >=0.5.0; 6 | 7 | import "./FullMath.sol"; 8 | 9 | /// @title FixedPoint96 10 | /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) 11 | /// @dev Used in SqrtPriceMath.sol 12 | library FixedPoint96 { 13 | uint8 internal constant RESOLUTION = 96; 14 | uint256 internal constant Q96 = 0x1000000000000000000000000; 15 | } 16 | 17 | /// @title Liquidity amount functions 18 | /// @notice Provides functions for computing liquidity amounts from token amounts and prices 19 | library LiquidityAmounts { 20 | /// @notice Downcasts uint256 to uint128 21 | /// @param x The uint258 to be downcasted 22 | /// @return y The passed value, downcasted to uint128 23 | function toUint128(uint256 x) private pure returns (uint128 y) { 24 | require((y = uint128(x)) == x); 25 | } 26 | 27 | /// @notice Computes the amount of liquidity received for a given amount of token0 and price range 28 | /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) 29 | /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary 30 | /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary 31 | /// @param amount0 The amount0 being sent in 32 | /// @return liquidity The amount of returned liquidity 33 | function getLiquidityForAmount0( 34 | uint160 sqrtRatioAX96, 35 | uint160 sqrtRatioBX96, 36 | uint256 amount0 37 | ) internal pure returns (uint128 liquidity) { 38 | if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); 39 | uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); 40 | return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); 41 | } 42 | 43 | /// @notice Computes the amount of liquidity received for a given amount of token1 and price range 44 | /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). 45 | /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary 46 | /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary 47 | /// @param amount1 The amount1 being sent in 48 | /// @return liquidity The amount of returned liquidity 49 | function getLiquidityForAmount1( 50 | uint160 sqrtRatioAX96, 51 | uint160 sqrtRatioBX96, 52 | uint256 amount1 53 | ) internal pure returns (uint128 liquidity) { 54 | if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); 55 | return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); 56 | } 57 | 58 | /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current 59 | /// pool prices and the prices at the tick boundaries 60 | /// @param sqrtRatioX96 A sqrt price representing the current pool prices 61 | /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary 62 | /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary 63 | /// @param amount0 The amount of token0 being sent in 64 | /// @param amount1 The amount of token1 being sent in 65 | /// @return liquidity The maximum amount of liquidity received 66 | function getLiquidityForAmounts( 67 | uint160 sqrtRatioX96, 68 | uint160 sqrtRatioAX96, 69 | uint160 sqrtRatioBX96, 70 | uint256 amount0, 71 | uint256 amount1 72 | ) internal pure returns (uint128 liquidity) { 73 | if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); 74 | 75 | if (sqrtRatioX96 <= sqrtRatioAX96) { 76 | liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); 77 | } else if (sqrtRatioX96 < sqrtRatioBX96) { 78 | uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); 79 | uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); 80 | 81 | liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; 82 | } else { 83 | liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /test/AllocatorBuffer.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 7 | import { GemMock } from "test/mocks/GemMock.sol"; 8 | 9 | contract AllocatorBufferTest is DssTest { 10 | using stdStorage for StdStorage; 11 | 12 | GemMock public gem; 13 | AllocatorBuffer public buffer; 14 | 15 | event Approve(address indexed asset, address indexed spender, uint256 amount); 16 | 17 | function setUp() public { 18 | gem = new GemMock(1_000_000 * 10**18); 19 | buffer = new AllocatorBuffer(); 20 | } 21 | 22 | function testConstructor() public { 23 | vm.expectEmit(true, true, true, true); 24 | emit Rely(address(this)); 25 | AllocatorBuffer b = new AllocatorBuffer(); 26 | assertEq(b.wards(address(this)), 1); 27 | } 28 | 29 | function testAuth() public { 30 | checkAuth(address(buffer), "AllocatorBuffer"); 31 | } 32 | 33 | function testModifiers() public { 34 | bytes4[] memory authedMethods = new bytes4[](1); 35 | authedMethods[0] = buffer.approve.selector; 36 | 37 | vm.startPrank(address(0xBEEF)); 38 | checkModifier(address(buffer), "AllocatorBuffer/not-authorized", authedMethods); 39 | vm.stopPrank(); 40 | } 41 | 42 | function testTransferApproveWithdraw() public { 43 | assertEq(gem.balanceOf(address(this)), gem.totalSupply()); 44 | assertEq(gem.balanceOf(address(buffer)), 0); 45 | gem.transfer(address(buffer), 10); 46 | assertEq(gem.balanceOf(address(this)), gem.totalSupply() - 10); 47 | assertEq(gem.balanceOf(address(buffer)), 10); 48 | assertEq(gem.allowance(address(buffer), address(this)), 0); 49 | vm.expectEmit(true, true, true, true); 50 | emit Approve(address(gem), address(this), 4); 51 | buffer.approve(address(gem), address(this), 4); 52 | assertEq(gem.allowance(address(buffer), address(this)), 4); 53 | gem.transferFrom(address(buffer), address(123), 4); 54 | assertEq(gem.balanceOf(address(buffer)), 6); 55 | assertEq(gem.balanceOf(address(123)), 4); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /test/AllocatorOracle.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import "src/AllocatorOracle.sol"; 7 | 8 | contract AllocatorOracleTest is DssTest { 9 | AllocatorOracle public oracle; 10 | 11 | function setUp() public { 12 | oracle = new AllocatorOracle(); 13 | } 14 | 15 | function testOracle() public { 16 | (bytes32 val, bool ok) = oracle.peek(); 17 | assertEq(val, bytes32(uint256(10**18))); 18 | assertTrue(ok); 19 | assertEq(oracle.read(), bytes32(uint256(10**18))); 20 | } 21 | 22 | function testPricing() public { 23 | uint256 par = 1 * 10**27; 24 | uint256 price = uint256(oracle.read()); // 1 * 10**18; 25 | uint256 colSupply = 1 * 10**12 * 10**18; 26 | uint256 colDebt = 1 * 10**6 * 10**45; // Imagine a scenario where the ilk only has 1M debt 27 | uint256 totDebt = 50 * 10**9 * 10**45; // Imagine a scenario where the tot Supply of DAI is 50B 28 | 29 | console.log("cage(ilk):"); 30 | console.log(""); 31 | uint256 tag = par * 10**18 / price; 32 | console.log("tag[ilk] =", tag); 33 | console.log(""); 34 | console.log("skim(ilk, buffer):"); 35 | console.log(""); 36 | uint256 owe = (colDebt / 10**27) * tag / 10**27; 37 | console.log("owe =", owe); 38 | uint256 wad = owe <= colSupply ? owe : colSupply; 39 | console.log("wad =", wad); 40 | uint256 gap = owe - wad; 41 | console.log("gap[ilk] =", gap); 42 | console.log(""); 43 | console.log("flow(ilk):"); 44 | console.log(""); 45 | wad = (colDebt / 10**27) * tag / 10**27; 46 | console.log("wad =", wad); 47 | uint256 fix = (wad - gap) * 10**27 / (totDebt / 10**27); 48 | console.log("fix[ilk] =", fix); 49 | console.log(""); 50 | console.log("cash(ilk,...):"); 51 | console.log(""); 52 | console.log("1 = wad * fix / 10^27 => wad = 10^27 / fix"); 53 | uint256 amtDaiNeeded = 10**27 / fix; 54 | console.log("Amount of wei DAI needed to get 1 wei of gem =", amtDaiNeeded); 55 | assertEq(amtDaiNeeded, 50_000); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /test/AllocatorRegistry.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { AllocatorRegistry } from "src/AllocatorRegistry.sol"; 7 | 8 | contract AllocatorRegistryTest is DssTest { 9 | AllocatorRegistry public registry; 10 | 11 | event File(bytes32 indexed ilk, bytes32 indexed what, address data); 12 | 13 | function setUp() public { 14 | registry = new AllocatorRegistry(); 15 | } 16 | 17 | function testConstructor() public { 18 | vm.expectEmit(true, true, true, true); 19 | emit Rely(address(this)); 20 | AllocatorRegistry r = new AllocatorRegistry(); 21 | assertEq(r.wards(address(this)), 1); 22 | } 23 | 24 | function testAuth() public { 25 | checkAuth(address(registry), "AllocatorRegistry"); 26 | } 27 | 28 | function testFileIlkAddress() public { 29 | // First check an invalid value 30 | vm.expectRevert("AllocatorRegistry/file-unrecognized-param"); 31 | registry.file("any", "an invalid value", address(123)); 32 | 33 | // Update value 34 | vm.expectEmit(true, true, true, true); 35 | emit File("any", "buffer", address(123)); 36 | registry.file("any", "buffer", address(123)); 37 | assertEq(registry.buffers("any"), address(123)); 38 | 39 | // Finally check that file is authed 40 | registry.deny(address(this)); 41 | vm.expectRevert("AllocatorRegistry/not-authorized"); 42 | registry.file("any", "data", address(123)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /test/AllocatorRoles.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import "src/AllocatorRoles.sol"; 7 | import { AuthedMock } from "test/mocks/AuthedMock.sol"; 8 | 9 | contract AllocatorRolesTest is DssTest { 10 | AllocatorRoles roles; 11 | AuthedMock authed; 12 | bytes32 ilk; 13 | 14 | event SetIlkAdmin(bytes32 indexed ilk, address user); 15 | event SetUserRole(bytes32 indexed ilk, address indexed who, uint8 indexed role, bool enabled); 16 | event SetRoleAction(bytes32 indexed ilk, uint8 indexed role, address indexed target, bytes4 sig, bool enabled); 17 | 18 | function setUp() public { 19 | ilk = "aaa"; 20 | roles = new AllocatorRoles(); 21 | authed = new AuthedMock(address(roles), ilk); 22 | } 23 | 24 | function testConstructor() public { 25 | vm.expectEmit(true, true, true, true); 26 | emit Rely(address(this)); 27 | AllocatorRoles r = new AllocatorRoles(); 28 | assertEq(r.wards(address(this)), 1); 29 | } 30 | 31 | function testAuth() public { 32 | checkAuth(address(roles), "AllocatorRoles"); 33 | } 34 | 35 | function testModifiers() public { 36 | bytes4[] memory authedMethods = new bytes4[](1); 37 | authedMethods[0] = roles.setIlkAdmin.selector; 38 | 39 | vm.startPrank(address(0xBEEF)); 40 | checkModifier(address(roles), "AllocatorRoles/not-authorized", authedMethods); 41 | vm.stopPrank(); 42 | } 43 | 44 | function testBasics() public { 45 | uint8 admin_role = 0; 46 | uint8 mod_role = 1; 47 | uint8 user_role = 2; 48 | uint8 max_role = 255; 49 | 50 | assertTrue(!roles.hasUserRole(ilk, address(this), admin_role)); 51 | assertTrue(!roles.hasUserRole(ilk, address(this), mod_role)); 52 | assertTrue(!roles.hasUserRole(ilk, address(this), user_role)); 53 | assertTrue(!roles.hasUserRole(ilk, address(this), max_role)); 54 | assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000000"), roles.userRoles(ilk, address(this))); 55 | 56 | vm.expectRevert("AllocatorRoles/ilk-not-authorized"); 57 | roles.setUserRole(ilk, address(this), admin_role, true); 58 | 59 | vm.expectEmit(true, true, true, true); 60 | emit SetIlkAdmin(ilk, address(this)); 61 | roles.setIlkAdmin(ilk, address(this)); 62 | vm.expectEmit(true, true, true, true); 63 | emit SetUserRole(ilk, address(this), admin_role, true); 64 | roles.setUserRole(ilk, address(this), admin_role, true); 65 | 66 | assertTrue( roles.hasUserRole(ilk, address(this), admin_role)); 67 | assertTrue(!roles.hasUserRole(ilk, address(this), mod_role)); 68 | assertTrue(!roles.hasUserRole(ilk, address(this), user_role)); 69 | assertTrue(!roles.hasUserRole(ilk, address(this), max_role)); 70 | assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000001"), roles.userRoles(ilk, address(this))); 71 | 72 | assertTrue(!roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()")))); 73 | vm.expectRevert("AuthedMock/not-authorized"); 74 | authed.exec(); 75 | 76 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), admin_role)); 77 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), mod_role)); 78 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), user_role)); 79 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), max_role)); 80 | vm.expectEmit(true, true, true, true); 81 | emit SetRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), true); 82 | roles.setRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), true); 83 | assertTrue( roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), admin_role)); 84 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), mod_role)); 85 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), user_role)); 86 | assertTrue(!roles.hasActionRole(ilk, address(authed), bytes4(keccak256("exec()")), max_role)); 87 | 88 | assertTrue(roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()")))); 89 | authed.exec(); 90 | assertTrue(authed.flag()); 91 | 92 | vm.expectEmit(true, true, true, true); 93 | emit SetRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), false); 94 | roles.setRoleAction(ilk, admin_role, address(authed), bytes4(keccak256("exec()")), false); 95 | assertTrue(!roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()")))); 96 | vm.expectRevert("AuthedMock/not-authorized"); 97 | authed.exec(); 98 | 99 | vm.expectEmit(true, true, true, true); 100 | emit SetUserRole(ilk, address(this), mod_role, true); 101 | roles.setUserRole(ilk, address(this), mod_role, true); 102 | 103 | assertTrue( roles.hasUserRole(ilk, address(this), admin_role)); 104 | assertTrue( roles.hasUserRole(ilk, address(this), mod_role)); 105 | assertTrue(!roles.hasUserRole(ilk, address(this), user_role)); 106 | assertTrue(!roles.hasUserRole(ilk, address(this), max_role)); 107 | assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000003"), roles.userRoles(ilk, address(this))); 108 | 109 | vm.expectEmit(true, true, true, true); 110 | emit SetUserRole(ilk, address(this), user_role, true); 111 | roles.setUserRole(ilk, address(this), user_role, true); 112 | 113 | assertTrue( roles.hasUserRole(ilk, address(this), admin_role)); 114 | assertTrue( roles.hasUserRole(ilk, address(this), mod_role)); 115 | assertTrue( roles.hasUserRole(ilk, address(this), user_role)); 116 | assertTrue(!roles.hasUserRole(ilk, address(this), max_role)); 117 | assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000007"), roles.userRoles(ilk, address(this))); 118 | 119 | vm.expectEmit(true, true, true, true); 120 | emit SetUserRole(ilk, address(this), mod_role, false); 121 | roles.setUserRole(ilk, address(this), mod_role, false); 122 | 123 | assertTrue( roles.hasUserRole(ilk, address(this), admin_role)); 124 | assertTrue(!roles.hasUserRole(ilk, address(this), mod_role)); 125 | assertTrue( roles.hasUserRole(ilk, address(this), user_role)); 126 | assertTrue(!roles.hasUserRole(ilk, address(this), max_role)); 127 | assertEq32(bytes32(hex"0000000000000000000000000000000000000000000000000000000000000005"), roles.userRoles(ilk, address(this))); 128 | 129 | vm.expectEmit(true, true, true, true); 130 | emit SetUserRole(ilk, address(this), max_role, true); 131 | roles.setUserRole(ilk, address(this), max_role, true); 132 | 133 | assertTrue( roles.hasUserRole(ilk, address(this), admin_role)); 134 | assertTrue(!roles.hasUserRole(ilk, address(this), mod_role)); 135 | assertTrue( roles.hasUserRole(ilk, address(this), user_role)); 136 | assertTrue( roles.hasUserRole(ilk, address(this), max_role)); 137 | assertEq32(bytes32(hex"8000000000000000000000000000000000000000000000000000000000000005"), roles.userRoles(ilk, address(this))); 138 | 139 | vm.expectEmit(true, true, true, true); 140 | emit SetRoleAction(ilk, max_role, address(authed), bytes4(keccak256("exec()")), true); 141 | roles.setRoleAction(ilk, max_role, address(authed), bytes4(keccak256("exec()")), true); 142 | assertTrue(roles.canCall(ilk, address(this), address(authed), bytes4(keccak256("exec()")))); 143 | authed.exec(); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /test/AllocatorVault.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { AllocatorVault } from "src/AllocatorVault.sol"; 7 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 8 | import { RolesMock } from "test/mocks/RolesMock.sol"; 9 | import { VatMock } from "test/mocks/VatMock.sol"; 10 | import { JugMock } from "test/mocks/JugMock.sol"; 11 | import { GemMock } from "test/mocks/GemMock.sol"; 12 | import { UsdsJoinMock } from "test/mocks/UsdsJoinMock.sol"; 13 | 14 | contract AllocatorVaultTest is DssTest { 15 | using stdStorage for StdStorage; 16 | 17 | VatMock public vat; 18 | JugMock public jug; 19 | GemMock public usds; 20 | UsdsJoinMock public usdsJoin; 21 | AllocatorBuffer public buffer; 22 | RolesMock public roles; 23 | AllocatorVault public vault; 24 | bytes32 public ilk; 25 | 26 | event Init(); 27 | event Draw(address indexed sender, uint256 wad); 28 | event Wipe(address indexed sender, uint256 wad); 29 | 30 | function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) { 31 | // Note: _divup(0,0) will return 0 differing from natural solidity division 32 | unchecked { 33 | z = x != 0 ? ((x - 1) / y) + 1 : 0; 34 | } 35 | } 36 | 37 | function setUp() public { 38 | ilk = "TEST-ILK"; 39 | vat = new VatMock(); 40 | jug = new JugMock(vat); 41 | usds = new GemMock(0); 42 | usdsJoin = new UsdsJoinMock(vat, usds); 43 | buffer = new AllocatorBuffer(); 44 | roles = new RolesMock(); 45 | vault = new AllocatorVault(address(roles), address(buffer), ilk, address(usdsJoin)); 46 | buffer.approve(address(usds), address(vault), type(uint256).max); 47 | 48 | vat.slip(ilk, address(vault), int256(1_000_000 * WAD)); 49 | vat.grab(ilk, address(vault), address(vault), address(0), int256(1_000_000 * WAD), 0); 50 | 51 | // Add some existing DAI assigned to usdsJoin to avoid a particular error 52 | stdstore.target(address(vat)).sig("dai(address)").with_key(address(usdsJoin)).depth(0).checked_write(100_000 * RAD); 53 | } 54 | 55 | function testConstructor() public { 56 | vm.expectEmit(true, true, true, true); 57 | emit Rely(address(this)); 58 | address join = address(new UsdsJoinMock(vat, usds)); 59 | AllocatorVault v = new AllocatorVault(address(0xBEEF), address(0xCCC), "SubDAO 1", join); 60 | assertEq(address(v.roles()), address(0xBEEF)); 61 | assertEq(v.buffer(), address(0xCCC)); 62 | assertEq(v.ilk(), "SubDAO 1"); 63 | assertEq(address(v.usdsJoin()), join); 64 | assertEq(v.wards(address(this)), 1); 65 | } 66 | 67 | function testAuth() public { 68 | checkAuth(address(vault), "AllocatorVault"); 69 | } 70 | 71 | function testModifiers() public { 72 | bytes4[] memory authedMethods = new bytes4[](2); 73 | authedMethods[0] = vault.draw.selector; 74 | authedMethods[1] = vault.wipe.selector; 75 | 76 | vm.startPrank(address(0xBEEF)); 77 | checkModifier(address(vault), "AllocatorVault/not-authorized", authedMethods); 78 | vm.stopPrank(); 79 | } 80 | 81 | function testFile() public { 82 | checkFileAddress(address(vault), "AllocatorVault", ["jug"]); 83 | } 84 | 85 | function testRoles() public { 86 | vm.startPrank(address(0xBEEF)); 87 | vm.expectRevert("AllocatorVault/not-authorized"); 88 | vault.file("jug", address(0)); 89 | roles.setOk(true); 90 | vault.file("jug", address(0)); 91 | } 92 | 93 | function testDrawWipe() public { 94 | vault.file("jug", address(jug)); 95 | (, uint256 art) = vat.urns(ilk, address(buffer)); 96 | assertEq(art, 0); 97 | vm.expectEmit(true, true, true, true); 98 | emit Draw(address(this), 50 * 10**18); 99 | vault.draw(50 * 10**18); 100 | (, art) = vat.urns(ilk, address(vault)); 101 | assertEq(art, 50 * 10**18); 102 | assertEq(vat.rate(), 10**27); 103 | assertEq(usds.balanceOf(address(buffer)), 50 * 10**18); 104 | vm.warp(block.timestamp + 1); 105 | vm.expectEmit(true, true, true, true); 106 | emit Draw(address(this), 50 * 10**18); 107 | vault.draw(50 * 10**18); 108 | (, art) = vat.urns(ilk, address(vault)); 109 | uint256 expectedArt = 50 * 10**18 + _divup(50 * 10**18 * 1000, 1001); 110 | assertEq(art, expectedArt); 111 | assertEq(vat.rate(), 1001 * 10**27 / 1000); 112 | assertEq(usds.balanceOf(address(buffer)), 100 * 10**18); 113 | assertGt(art * vat.rate(), 100.05 * 10**45); 114 | assertLt(art * vat.rate(), 100.06 * 10**45); 115 | vm.expectRevert("Gem/insufficient-balance"); 116 | vault.wipe(100.06 * 10**18); 117 | deal(address(usds), address(buffer), 100.06 * 10**18, true); 118 | assertEq(usds.balanceOf(address(buffer)), 100.06 * 10**18); 119 | vm.expectRevert(); 120 | vault.wipe(100.06 * 10**18); // It will try to wipe more art than existing, then reverts 121 | vm.expectEmit(true, true, true, true); 122 | emit Wipe(address(this), 100.05 * 10**18); 123 | vault.wipe(100.05 * 10**18); 124 | assertEq(usds.balanceOf(address(buffer)), 0.01 * 10**18); 125 | (, art) = vat.urns(ilk, address(vault)); 126 | assertEq(art, 1); // Dust which is impossible to wipe 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /test/funnels/UniV3Utils.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.8.16; 2 | 3 | import {LiquidityAmounts, FixedPoint96} from "src/funnels/uniV3/LiquidityAmounts.sol"; 4 | import {TickMath} from "src/funnels/uniV3/TickMath.sol"; 5 | import {FullMath} from "src/funnels/uniV3/FullMath.sol"; 6 | 7 | interface UniV3PoolLike { 8 | function slot0() external view returns ( 9 | uint160 sqrtPriceX96, 10 | int24 tick, 11 | uint16 observationIndex, 12 | uint16 observationCardinality, 13 | uint16 observationCardinalityNext, 14 | uint8 feeProtocol, 15 | bool unlocked 16 | ); 17 | 18 | struct PositionInfo { 19 | uint128 liquidity; 20 | uint256 feeGrowthInside0LastX128; 21 | uint256 feeGrowthInside1LastX128; 22 | uint128 tokensOwed0; 23 | uint128 tokensOwed1; 24 | } 25 | 26 | function positions(bytes32) external view returns (PositionInfo memory); 27 | } 28 | 29 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SafeCast.sol 30 | library SafeCast { 31 | function toInt128(int256 y) internal pure returns (int128 z) { 32 | require((z = int128(y)) == y); 33 | } 34 | 35 | function toInt256(uint256 y) internal pure returns (int256 z) { 36 | require(y < 2**255); 37 | z = int256(y); 38 | } 39 | } 40 | 41 | library UniV3Utils { 42 | using SafeCast for uint256; 43 | using SafeCast for int256; 44 | 45 | address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; 46 | address constant UNIV3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984; 47 | // https://github.com/Uniswap/v3-periphery/blob/464a8a49611272f7349c970e0fadb7ec1d3c1086/contracts/libraries/PoolAddress.sol#L33 48 | function getPool(address gem0, address gem1, uint24 fee) internal pure returns (UniV3PoolLike pool) { 49 | pool = UniV3PoolLike(address(uint160(uint256(keccak256(abi.encodePacked( 50 | hex'ff', 51 | UNIV3_FACTORY, 52 | keccak256(abi.encode(gem0, gem1, fee)), 53 | bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54) // POOL_INIT_CODE_HASH 54 | )))))); 55 | } 56 | 57 | function getLiquidity( 58 | address owner, 59 | address gem0, 60 | address gem1, 61 | uint24 fee, 62 | int24 tickLower, 63 | int24 tickUpper 64 | ) internal view returns (uint128 liquidity) { 65 | return getPool(gem0, gem1, fee).positions(keccak256(abi.encodePacked(owner, tickLower, tickUpper))).liquidity; 66 | } 67 | 68 | function getCurrentTick(address gem0, address gem1, uint24 fee) internal view returns (int24 tick) { 69 | (, tick,,,,,) = getPool(gem0, gem1, fee).slot0(); 70 | } 71 | 72 | function getLiquidityForAmts( 73 | UniV3PoolLike pool, 74 | int24 tickLower, 75 | int24 tickUpper, 76 | uint256 amt0Desired, 77 | uint256 amt1Desired 78 | ) internal view returns (uint128 liquidity) { 79 | (uint160 sqrtPriceX96, , , , , , ) = pool.slot0(); 80 | uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower); 81 | uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper); 82 | 83 | liquidity = LiquidityAmounts.getLiquidityForAmounts( 84 | sqrtPriceX96, 85 | sqrtRatioAX96, 86 | sqrtRatioBX96, 87 | amt0Desired, 88 | amt1Desired 89 | ); 90 | } 91 | 92 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/UnsafeMath.sol#L12 93 | function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { 94 | assembly { 95 | z := add(div(x, y), gt(mod(x, y), 0)) 96 | } 97 | } 98 | 99 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L153 100 | function getAmount0Delta( 101 | uint160 sqrtRatioAX96, 102 | uint160 sqrtRatioBX96, 103 | uint128 liquidity, 104 | bool roundUp 105 | ) internal pure returns (uint256 amount0) { 106 | unchecked { 107 | if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); 108 | 109 | uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; 110 | uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; 111 | 112 | require(sqrtRatioAX96 > 0); 113 | 114 | return 115 | roundUp 116 | ? divRoundingUp( 117 | FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), 118 | sqrtRatioAX96 119 | ) 120 | : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; 121 | } 122 | } 123 | 124 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L182 125 | function getAmount1Delta( 126 | uint160 sqrtRatioAX96, 127 | uint160 sqrtRatioBX96, 128 | uint128 liquidity, 129 | bool roundUp 130 | ) internal pure returns (uint256 amount1) { 131 | unchecked { 132 | if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); 133 | 134 | return 135 | roundUp 136 | ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) 137 | : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); 138 | } 139 | } 140 | 141 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L201 142 | function getAmount0Delta( 143 | uint160 sqrtRatioAX96, 144 | uint160 sqrtRatioBX96, 145 | int128 liquidity 146 | ) internal pure returns (int256 amount0) { 147 | unchecked { 148 | return 149 | liquidity < 0 150 | ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() 151 | : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); 152 | } 153 | } 154 | 155 | // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SqrtPriceMath.sol#L217C7-L217C7 156 | function getAmount1Delta( 157 | uint160 sqrtRatioAX96, 158 | uint160 sqrtRatioBX96, 159 | int128 liquidity 160 | ) internal pure returns (int256 amount1) { 161 | unchecked { 162 | return 163 | liquidity < 0 164 | ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() 165 | : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); 166 | } 167 | } 168 | 169 | // adapted from https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/UniswapV3Pool.sol#L327 170 | function getExpectedAmounts( 171 | address gem0, 172 | address gem1, 173 | uint24 fee, 174 | int24 tickLower, 175 | int24 tickUpper, 176 | uint128 liquidity, 177 | uint256 amt0Desired, 178 | uint256 amt1Desired, 179 | bool withdrawal 180 | ) internal view returns (uint256 expectedAmt0, uint256 expectedAmt1) { 181 | unchecked { 182 | UniV3PoolLike pool = getPool(gem0, gem1, fee); 183 | (uint160 sqrtPriceX96, int24 tick,,,,,) = pool.slot0(); 184 | int128 liqDelta = (int256(uint256(liquidity == 0 ? getLiquidityForAmts(pool, tickLower, tickUpper, amt0Desired, amt1Desired) : liquidity))).toInt128(); 185 | if (withdrawal) liqDelta = -liqDelta; 186 | 187 | int256 expectedAmt0_; 188 | int256 expectedAmt1_; 189 | if (tick < tickLower) { 190 | expectedAmt0_ = getAmount0Delta( 191 | TickMath.getSqrtRatioAtTick(tickLower), 192 | TickMath.getSqrtRatioAtTick(tickUpper), 193 | liqDelta 194 | ); 195 | } else if (tick < tickUpper) { 196 | expectedAmt0_ = getAmount0Delta( 197 | sqrtPriceX96, 198 | TickMath.getSqrtRatioAtTick(tickUpper), 199 | liqDelta 200 | ); 201 | expectedAmt1_ = getAmount1Delta( 202 | TickMath.getSqrtRatioAtTick(tickLower), 203 | sqrtPriceX96, 204 | liqDelta 205 | ); 206 | } else { 207 | expectedAmt1_ = getAmount1Delta( 208 | TickMath.getSqrtRatioAtTick(tickLower), 209 | TickMath.getSqrtRatioAtTick(tickUpper), 210 | liqDelta 211 | ); 212 | } 213 | 214 | expectedAmt0 = uint256(withdrawal ? -expectedAmt0_: expectedAmt0_); 215 | expectedAmt1 = uint256(withdrawal ? -expectedAmt1_: expectedAmt1_); 216 | } 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /test/funnels/automation/ConduitMover.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { ConduitMover } from "src/funnels/automation/ConduitMover.sol"; 7 | import { AllocatorRegistry } from "src/AllocatorRegistry.sol"; 8 | import { AllocatorRoles } from "src/AllocatorRoles.sol"; 9 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 10 | import { AllocatorConduitMock } from "test/mocks/AllocatorConduitMock.sol"; 11 | 12 | interface GemLike { 13 | function balanceOf(address) external view returns (uint256); 14 | } 15 | 16 | contract ConduitMoverTest is DssTest { 17 | event Kiss(address indexed usr); 18 | event Diss(address indexed usr); 19 | event SetConfig(address indexed from, address indexed to, address indexed gem, uint64 num, uint32 hop, uint128 lot); 20 | event Move(address indexed from, address indexed to, address indexed gem, uint128 lot); 21 | 22 | address public buffer; 23 | address public conduit1; 24 | address public conduit2; 25 | ConduitMover public mover; 26 | 27 | bytes32 constant ILK = "aaa"; 28 | address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; 29 | address constant FACILITATOR = address(0x1337); 30 | address constant KEEPER = address(0xb0b); 31 | uint8 constant MOVER_ROLE = uint8(1); 32 | 33 | function setUp() public { 34 | vm.createSelectFork(vm.envString("ETH_RPC_URL")); 35 | 36 | buffer = address(new AllocatorBuffer()); 37 | AllocatorRoles roles = new AllocatorRoles(); 38 | AllocatorRegistry registry = new AllocatorRegistry(); 39 | registry.file(ILK, "buffer", buffer); 40 | 41 | conduit1 = address(new AllocatorConduitMock(address(roles), address(registry))); 42 | conduit2 = address(new AllocatorConduitMock(address(roles), address(registry))); 43 | mover = new ConduitMover(ILK, buffer); 44 | 45 | // Allow mover to perform ILK operations on the conduits 46 | roles.setIlkAdmin(ILK, address(this)); 47 | roles.setRoleAction(ILK, MOVER_ROLE, conduit1, AllocatorConduitMock.deposit.selector, true); 48 | roles.setRoleAction(ILK, MOVER_ROLE, conduit1, AllocatorConduitMock.withdraw.selector, true); 49 | roles.setRoleAction(ILK, MOVER_ROLE, conduit2, AllocatorConduitMock.deposit.selector, true); 50 | roles.setUserRole(ILK, address(mover), MOVER_ROLE, true); 51 | 52 | // Allow conduits to transfer out funds out of the buffer 53 | AllocatorBuffer(buffer).approve(USDC, conduit1, type(uint256).max); 54 | AllocatorBuffer(buffer).approve(USDC, conduit2, type(uint256).max); 55 | 56 | // Give conduit1 some funds 57 | deal(USDC, buffer, 3_000 * 10**6, true); 58 | vm.prank(address(mover)); AllocatorConduitMock(conduit1).deposit(ILK, USDC, 3_000 * 10**6); 59 | 60 | // Set up keeper to move from conduit1 to conduit2 61 | mover.rely(FACILITATOR); 62 | vm.startPrank(FACILITATOR); 63 | mover.kiss(KEEPER); 64 | mover.setConfig(conduit1, conduit2, USDC, 10, 1 hours, uint128(1_000 * 10**6)); 65 | vm.stopPrank(); 66 | 67 | // Confirm initial parameters and amounts 68 | (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, conduit2, USDC); 69 | assertEq(num, 10); 70 | assertEq(hop, 1 hours); 71 | assertEq(zzz, 0); 72 | assertEq(lot, 1_000 * 10**6); 73 | assertEq(GemLike(USDC).balanceOf(buffer), 0); 74 | assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6); 75 | assertEq(GemLike(USDC).balanceOf(conduit2), 0); 76 | } 77 | 78 | function testConstructor() public { 79 | vm.expectEmit(true, true, true, true); 80 | emit Rely(address(this)); 81 | ConduitMover m = new ConduitMover("xyz", address(0xABC)); 82 | assertEq(m.ilk(), "xyz"); 83 | assertEq(m.buffer(), address(0xABC)); 84 | assertEq(m.wards(address(this)), 1); 85 | } 86 | 87 | function testAuth() public { 88 | checkAuth(address(mover), "ConduitMover"); 89 | } 90 | 91 | function testModifiers() public { 92 | bytes4[] memory authedMethods = new bytes4[](3); 93 | authedMethods[0] = ConduitMover.kiss.selector; 94 | authedMethods[1] = ConduitMover.diss.selector; 95 | authedMethods[2] = ConduitMover.setConfig.selector; 96 | 97 | vm.startPrank(address(0xBEEF)); 98 | checkModifier(address(mover), "ConduitMover/not-authorized", authedMethods); 99 | vm.stopPrank(); 100 | 101 | bytes4[] memory keeperMethods = new bytes4[](1); 102 | keeperMethods[0] = ConduitMover.move.selector; 103 | 104 | vm.startPrank(address(0xBEEF)); 105 | checkModifier(address(mover), "ConduitMover/non-keeper", keeperMethods); 106 | vm.stopPrank(); 107 | } 108 | 109 | function testKissDiss() public { 110 | address testAddress = address(0x123); 111 | assertEq(mover.buds(testAddress), 0); 112 | 113 | vm.expectEmit(true, true, true, true); 114 | emit Kiss(testAddress); 115 | mover.kiss(testAddress); 116 | assertEq(mover.buds(testAddress), 1); 117 | 118 | vm.expectEmit(true, true, true, true); 119 | emit Diss(testAddress); 120 | mover.diss(testAddress); 121 | assertEq(mover.buds(testAddress), 0); 122 | } 123 | 124 | function testSetConfig() public { 125 | vm.expectEmit(true, true, true, true); 126 | emit SetConfig(address(0x123), address(0x456), address(0x789), uint64(23), uint32(360 seconds), uint96(314)); 127 | mover.setConfig(address(0x123), address(0x456), address(0x789), uint64(23), uint32(360 seconds), uint96(314)); 128 | 129 | (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(address(0x123), address(0x456), address(0x789)); 130 | assertEq(num, 23); 131 | assertEq(hop, 360); 132 | assertEq(zzz, 0); 133 | assertEq(lot, 314); 134 | } 135 | 136 | function testMoveByKeeper() public { 137 | vm.expectEmit(true, true, true, true); 138 | emit Move(conduit1, conduit2, USDC, 1_000 * 10**6); 139 | vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC); 140 | 141 | assertEq(GemLike(USDC).balanceOf(conduit1), 2_000 * 10**6); 142 | assertEq(GemLike(USDC).balanceOf(conduit2), 1_000 * 10**6); 143 | assertEq(GemLike(USDC).balanceOf(buffer), 0); 144 | (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, conduit2, USDC); 145 | assertEq(num, 9); 146 | assertEq(hop, 1 hours); 147 | assertEq(zzz, block.timestamp); 148 | assertEq(lot, 1_000 * 10**6); 149 | 150 | vm.warp(block.timestamp + 1 hours - 1); 151 | vm.expectRevert("ConduitMover/too-soon"); 152 | vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC); 153 | 154 | vm.warp(block.timestamp + 1); 155 | vm.prank(KEEPER); mover.move(conduit1, conduit2, USDC); 156 | 157 | assertEq(GemLike(USDC).balanceOf(conduit1), 1_000 * 10**6); 158 | assertEq(GemLike(USDC).balanceOf(conduit2), 2_000 * 10**6); 159 | assertEq(GemLike(USDC).balanceOf(buffer), 0); 160 | (num, hop, zzz, lot) = mover.configs(conduit1, conduit2, USDC); 161 | assertEq(num, 8); 162 | assertEq(hop, 1 hours); 163 | assertEq(zzz, block.timestamp); 164 | assertEq(lot, 1_000 * 10**6); 165 | } 166 | 167 | function testMoveByKeeperToAndFromBuffer() public { 168 | // Set up keeper to move USDC between conduit1 and buffer 169 | vm.prank(FACILITATOR); mover.setConfig(conduit1, buffer, USDC, 10, 1 hours, uint128(1_000 * 10**6)); 170 | vm.prank(FACILITATOR); mover.setConfig(buffer, conduit1, USDC, 10, 1 hours, uint128(1_000 * 10**6)); 171 | assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6); 172 | assertEq(GemLike(USDC).balanceOf(buffer), 0); 173 | 174 | vm.expectEmit(true, true, true, true); 175 | emit Move(conduit1, buffer, USDC, 1_000 * 10**6); 176 | vm.prank(KEEPER); mover.move(conduit1, buffer, USDC); 177 | 178 | assertEq(GemLike(USDC).balanceOf(conduit1), 2_000 * 10**6); 179 | assertEq(GemLike(USDC).balanceOf(buffer), 1_000 * 10**6); 180 | (uint64 num, uint32 hop, uint32 zzz, uint128 lot) = mover.configs(conduit1, buffer, USDC); 181 | assertEq(num, 9); 182 | assertEq(hop, 1 hours); 183 | assertEq(zzz, block.timestamp); 184 | assertEq(lot, 1_000 * 10**6); 185 | 186 | vm.expectEmit(true, true, true, true); 187 | emit Move(buffer, conduit1, USDC, 1_000 * 10**6); 188 | vm.prank(KEEPER); mover.move(buffer, conduit1, USDC); 189 | 190 | assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6); 191 | assertEq(GemLike(USDC).balanceOf(buffer), 0); 192 | (num, hop, zzz, lot) = mover.configs(buffer, conduit1, USDC); 193 | assertEq(num, 9); 194 | assertEq(hop, 1 hours); 195 | assertEq(zzz, block.timestamp); 196 | assertEq(lot, 1_000 * 10**6); 197 | } 198 | 199 | function testMoveExceedingNum() public { 200 | vm.expectRevert("ConduitMover/exceeds-num"); 201 | vm.prank(KEEPER); mover.move(conduit1, conduit2, address(0x123)); 202 | } 203 | 204 | function testMoveLotWithdrawFail() public { 205 | vm.prank(FACILITATOR); mover.setConfig(conduit1, buffer, USDC, 10, 1 hours, uint128(3_100 * 10**6)); 206 | assertEq(GemLike(USDC).balanceOf(conduit1), 3_000 * 10**6); 207 | 208 | vm.expectRevert("ConduitMover/lot-withdraw-failed"); 209 | vm.prank(KEEPER); mover.move(conduit1, buffer, USDC); 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /test/funnels/automation/StableSwapper.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { Swapper, GemLike } from "src/funnels/Swapper.sol"; 7 | import { StableSwapper } from "src/funnels/automation/StableSwapper.sol"; 8 | import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol"; 9 | import { AllocatorRoles } from "src/AllocatorRoles.sol"; 10 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 11 | 12 | contract StableSwapperTest is DssTest { 13 | event Kiss(address indexed usr); 14 | event Diss(address indexed usr); 15 | event SetConfig(address indexed src, address indexed dst, uint128 num, uint32 hop, uint96 lot, uint96 req); 16 | event Swap(address indexed sender, address indexed src, address indexed dst, uint256 amt, uint256 out); 17 | 18 | AllocatorBuffer public buffer; 19 | Swapper public swapper; 20 | StableSwapper public stableSwapper; 21 | SwapperCalleeUniV3 public uniV3Callee; 22 | 23 | bytes32 constant ilk = "aaa"; 24 | bytes constant USDC_DAI_PATH = abi.encodePacked(USDC, uint24(100), DAI); 25 | bytes constant DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC); 26 | 27 | address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; 28 | address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; 29 | address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; 30 | 31 | address constant FACILITATOR = address(0x1337); 32 | address constant KEEPER = address(0xb0b); 33 | 34 | uint8 constant SWAPPER_ROLE = uint8(1); 35 | 36 | function setUp() public { 37 | vm.createSelectFork(vm.envString("ETH_RPC_URL")); 38 | 39 | buffer = new AllocatorBuffer(); 40 | AllocatorRoles roles = new AllocatorRoles(); 41 | swapper = new Swapper(address(roles), ilk, address(buffer)); 42 | uniV3Callee = new SwapperCalleeUniV3(UNIV3_ROUTER); 43 | stableSwapper = new StableSwapper(address(swapper)); 44 | 45 | roles.setIlkAdmin(ilk, address(this)); 46 | roles.setRoleAction(ilk, SWAPPER_ROLE, address(swapper), swapper.swap.selector, true); 47 | roles.setUserRole(ilk, FACILITATOR, SWAPPER_ROLE, true); 48 | roles.setUserRole(ilk, address(stableSwapper), SWAPPER_ROLE, true); 49 | 50 | swapper.setLimits(DAI, USDC, uint96(10_000 * WAD), 3600 seconds); 51 | swapper.setLimits(USDC, DAI, uint96(10_000 * 10**6), 3600 seconds); 52 | 53 | deal(DAI, address(buffer), 1_000_000 * WAD, true); 54 | deal(USDC, address(buffer), 1_000_000 * 10**6, true); 55 | buffer.approve(USDC, address(swapper), type(uint256).max); 56 | buffer.approve(DAI, address(swapper), type(uint256).max); 57 | 58 | stableSwapper.rely(FACILITATOR); 59 | vm.startPrank(FACILITATOR); 60 | stableSwapper.setConfig(DAI, USDC, 10, 360 seconds, uint96(1_000 * WAD), uint96(990 * 10**6)); 61 | stableSwapper.setConfig(USDC, DAI, 10, 360 seconds, uint96(1_000 * 10**6), uint96(990 * WAD)); 62 | stableSwapper.kiss(KEEPER); 63 | vm.stopPrank(); 64 | } 65 | 66 | function testConstructor() public { 67 | vm.expectEmit(true, true, true, true); 68 | emit Rely(address(this)); 69 | StableSwapper s = new StableSwapper(address(0xABC)); 70 | assertEq(address(s.swapper()), address(0xABC)); 71 | assertEq(s.wards(address(this)), 1); 72 | } 73 | 74 | function testAuth() public { 75 | checkAuth(address(stableSwapper), "StableSwapper"); 76 | } 77 | 78 | function testModifiers() public { 79 | bytes4[] memory authedMethods = new bytes4[](3); 80 | authedMethods[0] = StableSwapper.kiss.selector; 81 | authedMethods[1] = StableSwapper.diss.selector; 82 | authedMethods[2] = StableSwapper.setConfig.selector; 83 | 84 | vm.startPrank(address(0xBEEF)); 85 | checkModifier(address(stableSwapper), "StableSwapper/not-authorized", authedMethods); 86 | vm.stopPrank(); 87 | 88 | bytes4[] memory keeperMethods = new bytes4[](1); 89 | keeperMethods[0] = StableSwapper.swap.selector; 90 | 91 | vm.startPrank(address(0xBEEF)); 92 | checkModifier(address(stableSwapper), "StableSwapper/non-keeper", keeperMethods); 93 | vm.stopPrank(); 94 | } 95 | 96 | function testKissDiss() public { 97 | address testAddress = address(0x123); 98 | 99 | assertEq(stableSwapper.buds(testAddress), 0); 100 | vm.expectEmit(true, true, true, true); 101 | emit Kiss(testAddress); 102 | stableSwapper.kiss(testAddress); 103 | assertEq(stableSwapper.buds(testAddress), 1); 104 | vm.expectEmit(true, true, true, true); 105 | emit Diss(testAddress); 106 | stableSwapper.diss(testAddress); 107 | assertEq(stableSwapper.buds(testAddress), 0); 108 | } 109 | 110 | function testSetConfig() public { 111 | vm.expectEmit(true, true, true, true); 112 | emit SetConfig(address(0x123), address(0x456), uint128(23), uint32(360 seconds), uint96(314), uint96(42)); 113 | stableSwapper.setConfig(address(0x123), address(0x456), uint128(23), uint32(360 seconds), uint96(314), uint96(42)); 114 | 115 | (uint128 num, uint32 hop, uint32 zzz, uint96 lot, uint96 req) = stableSwapper.configs(address(0x123), address(0x456)); 116 | assertEq(num, 23); 117 | assertEq(hop, 360); 118 | assertEq(zzz, 0); 119 | assertEq(lot, 314); 120 | assertEq(req, 42); 121 | } 122 | 123 | function testSwapByKeeper() public { 124 | uint256 prevSrc = GemLike(USDC).balanceOf(address(buffer)); 125 | uint256 prevDst = GemLike(DAI).balanceOf(address(buffer)); 126 | (uint128 initUsdcDaiNum,,,,) = stableSwapper.configs(USDC, DAI); 127 | (uint128 initDaiUsdcNum,,,,) = stableSwapper.configs(DAI, USDC); 128 | uint32 initialTime = uint32(block.timestamp); 129 | 130 | vm.expectEmit(true, true, true, false); 131 | emit Swap(address(stableSwapper), USDC, DAI, 0, 0); 132 | vm.prank(KEEPER); uint256 out = stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH); 133 | 134 | assertGe(out, 990 * WAD); 135 | assertEq(GemLike(USDC).balanceOf(address(buffer)), prevSrc - 1_000 * 10**6); 136 | assertEq(GemLike(DAI).balanceOf(address(buffer)), prevDst + out); 137 | assertEq(GemLike(DAI).balanceOf(address(stableSwapper)), 0); 138 | assertEq(GemLike(USDC).balanceOf(address(stableSwapper)), 0); 139 | assertEq(GemLike(DAI).balanceOf(address(swapper)), 0); 140 | assertEq(GemLike(USDC).balanceOf(address(swapper)), 0); 141 | assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0); 142 | assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0); 143 | (uint128 usdcDaiNum,, uint32 usdcDaiZzz,,) = stableSwapper.configs(USDC, DAI); 144 | assertEq(usdcDaiNum, initUsdcDaiNum - 1); 145 | assertEq(usdcDaiZzz, initialTime); 146 | 147 | vm.warp(initialTime + 180); 148 | vm.expectRevert("StableSwapper/too-soon"); 149 | vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH); 150 | 151 | vm.warp(initialTime + 360); 152 | vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 990 * WAD, address(uniV3Callee), USDC_DAI_PATH); 153 | 154 | (usdcDaiNum,, usdcDaiZzz,,) = stableSwapper.configs(USDC, DAI); 155 | assertEq(usdcDaiNum, initUsdcDaiNum - 2); 156 | assertEq(usdcDaiZzz, initialTime + 360); 157 | 158 | prevSrc = GemLike(DAI).balanceOf(address(buffer)); 159 | prevDst = GemLike(USDC).balanceOf(address(buffer)); 160 | 161 | vm.expectEmit(true, true, true, false); 162 | emit Swap(address(stableSwapper), DAI, USDC, 0, 0); 163 | vm.prank(KEEPER); out = stableSwapper.swap(DAI, USDC, 990 * 10**6, address(uniV3Callee), DAI_USDC_PATH); 164 | 165 | assertGe(out, 990 * 10**6); 166 | assertEq(GemLike(DAI).balanceOf(address(buffer)), prevSrc - 1_000 * WAD); 167 | assertEq(GemLike(USDC).balanceOf(address(buffer)), prevDst + out); 168 | assertEq(GemLike(DAI).balanceOf(address(stableSwapper)), 0); 169 | assertEq(GemLike(USDC).balanceOf(address(stableSwapper)), 0); 170 | assertEq(GemLike(DAI).balanceOf(address(swapper)), 0); 171 | assertEq(GemLike(USDC).balanceOf(address(swapper)), 0); 172 | assertEq(GemLike(DAI).balanceOf(address(uniV3Callee)), 0); 173 | assertEq(GemLike(USDC).balanceOf(address(uniV3Callee)), 0); 174 | (uint128 daiUsdcNum,, uint32 daiUsdcZzz,,) = stableSwapper.configs(DAI, USDC); 175 | assertEq(daiUsdcNum, initDaiUsdcNum - 1); 176 | assertEq(daiUsdcZzz, initialTime + 360); 177 | } 178 | 179 | function testSwapMinZero() public { 180 | vm.expectEmit(true, true, true, false); 181 | emit Swap(address(stableSwapper), USDC, DAI, 0, 0); 182 | vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, 0, address(uniV3Callee), USDC_DAI_PATH); 183 | } 184 | 185 | function testSwapExceedingNum() public { 186 | vm.expectRevert("StableSwapper/exceeds-num"); 187 | vm.prank(KEEPER); stableSwapper.swap(USDC, USDC, 0, address(uniV3Callee), USDC_DAI_PATH); 188 | } 189 | 190 | function testSwapWithMinTooSmall() public { 191 | (,,,, uint96 req) = stableSwapper.configs(USDC, DAI); 192 | vm.expectRevert("StableSwapper/min-too-small"); 193 | vm.prank(KEEPER); stableSwapper.swap(USDC, DAI, req - 1, address(uniV3Callee), USDC_DAI_PATH); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /test/funnels/automation/VaultMinter.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import "dss-test/DssTest.sol"; 6 | import { VaultMinter } from "src/funnels/automation/VaultMinter.sol"; 7 | import { AllocatorRoles } from "src/AllocatorRoles.sol"; 8 | import { AllocatorVault } from "src/AllocatorVault.sol"; 9 | import { AllocatorBuffer } from "src/AllocatorBuffer.sol"; 10 | import { VatMock } from "test/mocks/VatMock.sol"; 11 | import { JugMock } from "test/mocks/JugMock.sol"; 12 | import { GemMock } from "test/mocks/GemMock.sol"; 13 | import { UsdsJoinMock } from "test/mocks/UsdsJoinMock.sol"; 14 | 15 | contract VaultMinterTest is DssTest { 16 | using stdStorage for StdStorage; 17 | 18 | event Kiss(address indexed usr); 19 | event Diss(address indexed usr); 20 | event SetConfig(int64 num, uint32 hop, uint128 lot); 21 | event Draw(uint128 lot); 22 | event Wipe(uint128 lot); 23 | 24 | VatMock public vat; 25 | JugMock public jug; 26 | GemMock public usds; 27 | UsdsJoinMock public usdsJoin; 28 | AllocatorBuffer public buffer; 29 | AllocatorRoles public roles; 30 | AllocatorVault public vault; 31 | VaultMinter public minter; 32 | 33 | bytes32 constant ILK = "aaa"; 34 | address constant FACILITATOR = address(0x1337); 35 | address constant KEEPER = address(0xb0b); 36 | uint8 constant MINTER_ROLE = uint8(1); 37 | 38 | function setUp() public { 39 | vat = new VatMock(); 40 | jug = new JugMock(vat); 41 | usds = new GemMock(0); 42 | usdsJoin = new UsdsJoinMock(vat, usds); 43 | buffer = new AllocatorBuffer(); 44 | roles = new AllocatorRoles(); 45 | vault = new AllocatorVault(address(roles), address(buffer), ILK, address(usdsJoin)); 46 | vault.file("jug", address(jug)); 47 | buffer.approve(address(usds), address(vault), type(uint256).max); 48 | 49 | vat.slip(ILK, address(vault), int256(1_000_000 * WAD)); 50 | vat.grab(ILK, address(vault), address(vault), address(0), int256(1_000_000 * WAD), 0); 51 | 52 | minter = new VaultMinter(address(vault)); 53 | 54 | // Allow minter to perform operations in the vault 55 | roles.setIlkAdmin(ILK, address(this)); 56 | roles.setRoleAction(ILK, MINTER_ROLE, address(vault), AllocatorVault.draw.selector, true); 57 | roles.setRoleAction(ILK, MINTER_ROLE, address(vault), AllocatorVault.wipe.selector, true); 58 | roles.setUserRole(ILK, address(minter), MINTER_ROLE, true); 59 | 60 | // Set up keeper to mint and burn 61 | minter.rely(FACILITATOR); 62 | vm.prank(FACILITATOR); minter.kiss(KEEPER); 63 | 64 | vm.warp(1 hours); 65 | } 66 | 67 | function testConstructor() public { 68 | vm.expectEmit(true, true, true, true); 69 | emit Rely(address(this)); 70 | VaultMinter m = new VaultMinter(address(0xABC)); 71 | assertEq(m.vault(), address(0xABC)); 72 | assertEq(m.wards(address(this)), 1); 73 | } 74 | 75 | function testAuth() public { 76 | checkAuth(address(minter), "VaultMinter"); 77 | } 78 | 79 | function testModifiers() public { 80 | bytes4[] memory authedMethods = new bytes4[](3); 81 | authedMethods[0] = VaultMinter.kiss.selector; 82 | authedMethods[1] = VaultMinter.diss.selector; 83 | authedMethods[2] = VaultMinter.setConfig.selector; 84 | 85 | vm.startPrank(address(0xBEEF)); 86 | checkModifier(address(minter), "VaultMinter/not-authorized", authedMethods); 87 | vm.stopPrank(); 88 | 89 | bytes4[] memory keeperMethods = new bytes4[](2); 90 | keeperMethods[0] = VaultMinter.draw.selector; 91 | keeperMethods[1] = VaultMinter.wipe.selector; 92 | 93 | vm.startPrank(address(0xBEEF)); 94 | checkModifier(address(minter), "VaultMinter/non-keeper", keeperMethods); 95 | vm.stopPrank(); 96 | } 97 | 98 | function testKissDiss() public { 99 | address testAddress = address(0x123); 100 | assertEq(minter.buds(testAddress), 0); 101 | 102 | vm.expectEmit(true, true, true, true); 103 | emit Kiss(testAddress); 104 | minter.kiss(testAddress); 105 | assertEq(minter.buds(testAddress), 1); 106 | 107 | vm.expectEmit(true, true, true, true); 108 | emit Diss(testAddress); 109 | minter.diss(testAddress); 110 | assertEq(minter.buds(testAddress), 0); 111 | } 112 | 113 | function testSetConfig() public { 114 | vm.expectEmit(true, true, true, true); 115 | emit SetConfig(int64(23), uint32(360 seconds), uint128(314)); 116 | minter.setConfig(int64(23), uint32(360 seconds), uint128(314)); 117 | 118 | (int64 num, uint32 hop, uint32 zzz, uint128 lot) = minter.config(); 119 | assertEq(num, 23); 120 | assertEq(hop, 360); 121 | assertEq(zzz, 0); 122 | assertEq(lot, 314); 123 | 124 | vm.expectEmit(true, true, true, true); 125 | emit SetConfig(-int64(10), uint32(180 seconds), uint128(411)); 126 | minter.setConfig(-int64(10), uint32(180 seconds), uint128(411)); 127 | 128 | (num, hop, zzz, lot) = minter.config(); 129 | assertEq(num, -int64(10)); 130 | assertEq(hop, 180); 131 | assertEq(zzz, 0); 132 | assertEq(lot, 411); 133 | } 134 | 135 | function testDrawWipeByKeeper() public { 136 | minter.setConfig(int64(10), uint32(1 hours), uint128(1_000 * WAD)); 137 | 138 | assertEq(usds.balanceOf(address(buffer)), 0); 139 | (int64 num, uint32 hop, uint32 zzz, uint128 lot) = minter.config(); 140 | assertEq(num, 10); 141 | assertEq(hop, 1 hours); 142 | assertEq(zzz, 0); 143 | assertEq(lot, 1_000 * WAD); 144 | 145 | vm.expectEmit(true, true, true, true); 146 | emit Draw(uint128(1_000 * WAD)); 147 | vm.prank(KEEPER); minter.draw(); 148 | 149 | assertEq(usds.balanceOf(address(buffer)), 1_000 * WAD); 150 | (num, hop, zzz, lot) = minter.config(); 151 | assertEq(num, 9); 152 | assertEq(hop, 1 hours); 153 | assertEq(zzz, block.timestamp); 154 | assertEq(lot, 1_000 * WAD); 155 | 156 | vm.warp(block.timestamp + 1 hours - 1); 157 | vm.expectRevert("VaultMinter/too-soon"); 158 | vm.prank(KEEPER); minter.draw(); 159 | 160 | vm.warp(block.timestamp + 1); 161 | vm.prank(KEEPER); minter.draw(); 162 | 163 | assertEq(usds.balanceOf(address(buffer)), 2_000 * WAD); 164 | (num, hop, zzz, lot) = minter.config(); 165 | assertEq(num, 8); 166 | assertEq(hop, 1 hours); 167 | assertEq(zzz, block.timestamp); 168 | assertEq(lot, 1_000 * WAD); 169 | 170 | minter.setConfig(-int64(10), uint32(1 hours), uint128(100 * WAD)); 171 | 172 | (num, hop, zzz, lot) = minter.config(); 173 | assertEq(num, -10); 174 | assertEq(hop, 1 hours); 175 | assertEq(zzz, 0); 176 | assertEq(lot, 100 * WAD); 177 | 178 | vm.expectEmit(true, true, true, true); 179 | emit Wipe(uint128(100 * WAD)); 180 | vm.prank(KEEPER); minter.wipe(); 181 | 182 | assertEq(usds.balanceOf(address(buffer)), 1_900 * WAD); 183 | (num, hop, zzz, lot) = minter.config(); 184 | assertEq(num, -9); 185 | assertEq(hop, 1 hours); 186 | assertEq(zzz, block.timestamp); 187 | assertEq(lot, 100 * WAD); 188 | 189 | vm.warp(block.timestamp + 1 hours - 1); 190 | vm.expectRevert("VaultMinter/too-soon"); 191 | vm.prank(KEEPER); minter.wipe(); 192 | 193 | vm.warp(block.timestamp + 1); 194 | vm.prank(KEEPER); minter.wipe(); 195 | 196 | assertEq(usds.balanceOf(address(buffer)), 1_800 * WAD); 197 | (num, hop, zzz, lot) = minter.config(); 198 | assertEq(num, -8); 199 | assertEq(hop, 1 hours); 200 | assertEq(zzz, block.timestamp); 201 | assertEq(lot, 100 * WAD); 202 | } 203 | 204 | function testMintBurnExceedingNum() public { 205 | vm.expectRevert("VaultMinter/exceeds-num"); 206 | vm.prank(KEEPER); minter.draw(); 207 | vm.expectRevert("VaultMinter/exceeds-num"); 208 | vm.prank(KEEPER); minter.wipe(); 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /test/funnels/callees/SwapperCalleePsm.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.16; 3 | 4 | import "dss-test/DssTest.sol"; 5 | import { SwapperCalleePsm } from "src/funnels/callees/SwapperCalleePsm.sol"; 6 | import { PsmMock } from "test/mocks/PsmMock.sol"; 7 | 8 | interface GemLike { 9 | function balanceOf(address) external view returns (uint256); 10 | function transfer(address, uint256) external; 11 | function decimals() external view returns (uint8); 12 | } 13 | 14 | contract SwapperCalleePsmTest is DssTest { 15 | 16 | PsmMock psm; 17 | PsmMock psmUSDT; 18 | SwapperCalleePsm callee; 19 | SwapperCalleePsm calleeUSDT; 20 | 21 | address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; 22 | address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; 23 | address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; 24 | 25 | function setUp() public { 26 | vm.createSelectFork(vm.envString("ETH_RPC_URL")); 27 | 28 | psm = new PsmMock(DAI, USDC); 29 | callee = new SwapperCalleePsm(address(psm)); 30 | psm.rely(address(callee)); 31 | callee.rely(address(this)); 32 | 33 | psmUSDT = new PsmMock(DAI, USDT); 34 | calleeUSDT = new SwapperCalleePsm(address(psmUSDT)); 35 | psmUSDT.rely(address(calleeUSDT)); 36 | calleeUSDT.rely(address(this)); 37 | 38 | deal(DAI, address(this), 1_000_000 * WAD, true); 39 | deal(DAI, address(psm), 1_000_000 * WAD, true); 40 | deal(DAI, address(psmUSDT), 1_000_000 * WAD, true); 41 | deal(USDC, address(this), 1_000_000 * 10**6, true); 42 | deal(USDC, psm.pocket(), 1_000_000 * 10**6, true); 43 | deal(USDT, address(this), 1_000_000 * 10**6, true); 44 | deal(USDT, psmUSDT.pocket(), 1_000_000 * 10**6, true); 45 | } 46 | 47 | function testConstructor() public { 48 | vm.expectEmit(true, true, true, true); 49 | emit Rely(address(this)); 50 | SwapperCalleePsm c = new SwapperCalleePsm(address(psm)); 51 | assertEq(c.psm(), address(psm)); 52 | assertEq(c.gem(), USDC); 53 | assertEq(c.to18ConversionFactor(), 10**12); 54 | assertEq(c.wards(address(this)), 1); 55 | } 56 | 57 | function testAuth() public { 58 | checkAuth(address(callee), "SwapperCalleePsm"); 59 | } 60 | 61 | function testModifiers() public { 62 | bytes4[] memory authedMethods = new bytes4[](1); 63 | authedMethods[0] = callee.swapCallback.selector; 64 | 65 | vm.startPrank(address(0xBEEF)); 66 | checkModifier(address(callee), "SwapperCalleePsm/not-authorized", authedMethods); 67 | vm.stopPrank(); 68 | } 69 | 70 | function checkPsmSwap(SwapperCalleePsm callee_, address from, address to) public { 71 | uint256 prevFrom = GemLike(from).balanceOf(address(this)); 72 | uint256 prevTo = GemLike(to).balanceOf(address(this)); 73 | uint8 fromDecimals = GemLike(from).decimals(); 74 | uint8 toDecimals = GemLike(to).decimals(); 75 | 76 | GemLike(from).transfer(address(callee_), 10_000 * 10**fromDecimals); 77 | callee_.swapCallback(from, to, 10_000 * 10**fromDecimals, 0, address(this), ""); 78 | 79 | assertEq(GemLike(from).balanceOf(address(this)), prevFrom - 10_000 * 10**fromDecimals); 80 | assertEq(GemLike(to ).balanceOf(address(this)), prevTo + 10_000 * 10**toDecimals ); 81 | assertEq(GemLike(from).balanceOf(address(callee_)), 0); 82 | assertEq(GemLike(to ).balanceOf(address(callee_)), 0); 83 | } 84 | 85 | function testDaiToGemSwap() public { 86 | checkPsmSwap(callee, DAI, USDC); 87 | checkPsmSwap(calleeUSDT, DAI, USDT); 88 | } 89 | 90 | function testGemToDaiSwap() public { 91 | checkPsmSwap(callee, USDC, DAI); 92 | checkPsmSwap(calleeUSDT, DAI, USDT); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /test/funnels/callees/SwapperCalleeUniV3.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.16; 3 | 4 | import "dss-test/DssTest.sol"; 5 | import { SwapperCalleeUniV3 } from "src/funnels/callees/SwapperCalleeUniV3.sol"; 6 | 7 | interface GemLike { 8 | function balanceOf(address) external view returns (uint256); 9 | function transfer(address, uint256) external; 10 | function decimals() external view returns (uint8); 11 | } 12 | 13 | contract SwapperCalleeUniV3Test is DssTest { 14 | 15 | SwapperCalleeUniV3 public callee; 16 | 17 | address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; 18 | address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; 19 | address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; 20 | address constant UNIV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; 21 | 22 | function setUp() public { 23 | vm.createSelectFork(vm.envString("ETH_RPC_URL")); 24 | 25 | callee = new SwapperCalleeUniV3(UNIV3_ROUTER); 26 | 27 | deal(DAI, address(this), 1_000_000 * WAD, true); 28 | deal(USDC, address(this), 1_000_000 * 10**6, true); 29 | deal(USDT, address(this), 1_000_000 * 10**6, true); 30 | } 31 | 32 | function testConstructor() public { 33 | SwapperCalleeUniV3 c = new SwapperCalleeUniV3(address(0xBEEF)); 34 | assertEq(address(c.uniV3Router()), address(0xBEEF)); 35 | } 36 | 37 | function checkStableSwap(address from, address to, bytes memory path) public { 38 | uint256 prevFrom = GemLike(from).balanceOf(address(this)); 39 | uint256 prevTo = GemLike(to).balanceOf(address(this)); 40 | uint8 fromDecimals = GemLike(from).decimals(); 41 | uint8 toDecimals = GemLike(to).decimals(); 42 | 43 | GemLike(from).transfer(address(callee), 10_000 * 10**fromDecimals); 44 | callee.swapCallback(from, to, 10_000 * 10**fromDecimals, 9000 * 10**toDecimals, address(this), path); 45 | 46 | assertEq(GemLike(from).balanceOf(address(this)), prevFrom - 10_000 * 10**fromDecimals); 47 | assertGe(GemLike(to).balanceOf(address(this)), prevTo + 9000 * 10**toDecimals); 48 | assertEq(GemLike(from).balanceOf(address(callee)), 0); 49 | assertEq(GemLike(to).balanceOf(address(callee)), 0); 50 | } 51 | 52 | function testSwapUsdt() public { 53 | bytes memory USDT_DAI_PATH = abi.encodePacked(USDT, uint24(100), DAI); 54 | checkStableSwap(USDT, DAI, USDT_DAI_PATH); 55 | checkStableSwap(USDT, DAI, USDT_DAI_PATH); // swapping a 2nd time to verify that USDT allowance has been cleared after the 1st swap 56 | } 57 | 58 | function testSwapShortPath() public { 59 | bytes memory DAI_USDC_PATH = abi.encodePacked(DAI, uint24(100), USDC); 60 | checkStableSwap(DAI, USDC, DAI_USDC_PATH); 61 | } 62 | 63 | function testSwapLongPath() public { 64 | bytes memory USDC_USDT_DAI_PATH = abi.encodePacked(USDC, uint24(100), USDT, uint24(100), DAI); 65 | checkStableSwap(USDC, DAI, USDC_USDT_DAI_PATH); 66 | } 67 | 68 | function testSwapInvalidPath() public { 69 | bytes memory USDT_DAI_PATH = abi.encodePacked(USDT, uint24(100), DAI); 70 | 71 | vm.expectRevert("SwapperCalleeUniV3/invalid-path"); 72 | this.checkStableSwap(USDC, DAI, USDT_DAI_PATH); // src != path[0] 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /test/mocks/AllocatorConduitMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: © 2023 Dai Foundation 2 | // SPDX-License-Identifier: AGPL-3.0-or-later 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Affero General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Affero General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU Affero General Public License 15 | // along with this program. If not, see . 16 | 17 | pragma solidity ^0.8.16; 18 | 19 | import "src/IAllocatorConduit.sol"; 20 | 21 | interface RolesLike { 22 | function canCall(bytes32, address, address, bytes4) external view returns (bool); 23 | } 24 | 25 | interface RegistryLike { 26 | function buffers(bytes32) external view returns (address); 27 | } 28 | 29 | interface GemLike { 30 | function transfer(address, uint256) external; 31 | function transferFrom(address, address, uint256) external; 32 | } 33 | 34 | contract AllocatorConduitMock is IAllocatorConduit { 35 | // --- storage variables --- 36 | 37 | mapping(address => uint256) public wards; 38 | mapping(bytes32 => mapping(address => uint256)) public positions; 39 | 40 | // --- immutables --- 41 | 42 | RolesLike public immutable roles; 43 | RegistryLike public immutable registry; 44 | 45 | // --- events --- 46 | 47 | event Rely(address indexed usr); 48 | event Deny(address indexed usr); 49 | event SetRoles(bytes32 indexed ilk, address roles_); 50 | 51 | // --- modifiers --- 52 | 53 | modifier auth() { 54 | require(wards[msg.sender] == 1, "AllocatorConduitMock/not-authorized"); 55 | _; 56 | } 57 | 58 | modifier ilkAuth(bytes32 ilk) { 59 | require(roles.canCall(ilk, msg.sender, address(this), msg.sig), "AllocatorConduitMock/ilk-not-authorized"); 60 | _; 61 | } 62 | 63 | // --- constructor --- 64 | 65 | constructor(address roles_, address registry_) { 66 | roles = RolesLike(roles_); 67 | registry = RegistryLike(registry_); 68 | } 69 | 70 | // --- getters --- 71 | 72 | function maxDeposit(bytes32 ilk, address asset) external pure returns (uint256 maxDeposit_) { 73 | ilk;asset; 74 | maxDeposit_ = type(uint256).max; 75 | } 76 | 77 | function maxWithdraw(bytes32 ilk, address asset) external view returns (uint256 maxWithdraw_) { 78 | maxWithdraw_ = positions[ilk][asset]; 79 | } 80 | 81 | // --- admininstration --- 82 | 83 | function rely(address usr) external auth { 84 | wards[usr] = 1; 85 | emit Rely(usr); 86 | } 87 | 88 | function deny(address usr) external auth { 89 | wards[usr] = 0; 90 | emit Deny(usr); 91 | } 92 | 93 | // --- functions --- 94 | 95 | function deposit(bytes32 ilk, address asset, uint256 amount) external ilkAuth(ilk) { 96 | address buffer = registry.buffers(ilk); 97 | GemLike(asset).transferFrom(buffer, address(this), amount); 98 | positions[ilk][asset] += amount; 99 | emit Deposit(ilk, asset, buffer, amount); 100 | } 101 | 102 | function withdraw(bytes32 ilk, address asset, uint256 maxAmount) external ilkAuth(ilk) returns (uint256 amount) { 103 | uint256 balance = positions[ilk][asset]; 104 | amount = balance < maxAmount ? balance : maxAmount; 105 | positions[ilk][asset] = balance - amount; 106 | address buffer = registry.buffers(ilk); 107 | GemLike(asset).transfer(buffer, amount); 108 | emit Withdraw(ilk, asset, buffer, amount); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /test/mocks/AuthedMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | interface RolesLike { 6 | function canCall(bytes32, address, address, bytes4) external view returns (bool); 7 | } 8 | 9 | contract AuthedMock { 10 | bool public flag; 11 | 12 | RolesLike public immutable roles; 13 | bytes32 public immutable ilk; 14 | 15 | constructor(address roles_, bytes32 ilk_) { 16 | roles = RolesLike(roles_); 17 | ilk = ilk_; 18 | } 19 | 20 | modifier auth() { 21 | require(roles.canCall(ilk, msg.sender, address(this), msg.sig), "AuthedMock/not-authorized"); 22 | _; 23 | } 24 | 25 | function exec() public auth { 26 | flag = true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /test/mocks/CalleeMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | interface GemLike { 6 | function balanceOf(address) external view returns (uint256); 7 | function transfer(address, uint256) external; 8 | } 9 | 10 | contract CalleeMock { 11 | uint256 random; 12 | 13 | function swapCallback(address, address dst, uint256, uint256, address, bytes calldata) external { 14 | GemLike(dst).transfer(msg.sender, GemLike(dst).balanceOf(address(this))); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /test/mocks/Gem0Mock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import { GemMock } from "test/mocks/GemMock.sol"; 6 | 7 | contract Gem0Mock is GemMock(1_000_000*10**18) { 8 | } 9 | -------------------------------------------------------------------------------- /test/mocks/Gem1Mock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import { GemMock } from "test/mocks/GemMock.sol"; 6 | 7 | contract Gem1Mock is GemMock(1_000_000*10**18) { 8 | } 9 | -------------------------------------------------------------------------------- /test/mocks/GemMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | contract GemMock { 6 | mapping (address => uint256) public balanceOf; 7 | mapping (address => mapping (address => uint256)) public allowance; 8 | 9 | uint256 public totalSupply; 10 | 11 | constructor(uint256 initialSupply) { 12 | mint(msg.sender, initialSupply); 13 | } 14 | 15 | function approve(address spender, uint256 value) external returns (bool) { 16 | allowance[msg.sender][spender] = value; 17 | return true; 18 | } 19 | 20 | function transfer(address to, uint256 value) external returns (bool) { 21 | uint256 balance = balanceOf[msg.sender]; 22 | require(balance >= value, "Gem/insufficient-balance"); 23 | 24 | unchecked { 25 | balanceOf[msg.sender] = balance - value; 26 | balanceOf[to] += value; 27 | } 28 | return true; 29 | } 30 | 31 | function transferFrom(address from, address to, uint256 value) external returns (bool) { 32 | uint256 balance = balanceOf[from]; 33 | require(balance >= value, "Gem/insufficient-balance"); 34 | 35 | if (from != msg.sender) { 36 | uint256 allowed = allowance[from][msg.sender]; 37 | if (allowed != type(uint256).max) { 38 | require(allowed >= value, "Gem/insufficient-allowance"); 39 | 40 | unchecked { 41 | allowance[from][msg.sender] = allowed - value; 42 | } 43 | } 44 | } 45 | 46 | unchecked { 47 | balanceOf[from] = balance - value; 48 | balanceOf[to] += value; 49 | } 50 | return true; 51 | } 52 | 53 | function mint(address to, uint256 value) public { 54 | unchecked { 55 | balanceOf[to] = balanceOf[to] + value; 56 | } 57 | totalSupply = totalSupply + value; 58 | } 59 | 60 | function burn(address from, uint256 value) external { 61 | uint256 balance = balanceOf[from]; 62 | require(balance >= value, "Gem/insufficient-balance"); 63 | 64 | if (from != msg.sender) { 65 | uint256 allowed = allowance[from][msg.sender]; 66 | if (allowed != type(uint256).max) { 67 | require(allowed >= value, "Gem/insufficient-allowance"); 68 | 69 | unchecked { 70 | allowance[from][msg.sender] = allowed - value; 71 | } 72 | } 73 | } 74 | 75 | unchecked { 76 | balanceOf[from] = balance - value; 77 | totalSupply = totalSupply - value; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /test/mocks/JugMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import { VatMock } from "test/mocks/VatMock.sol"; 6 | 7 | contract JugMock { 8 | VatMock vat; 9 | 10 | uint256 public duty = 1001 * 10**27 / 1000; 11 | uint256 public rho = block.timestamp; 12 | 13 | constructor(VatMock vat_) { 14 | vat = vat_; 15 | } 16 | 17 | function drip(bytes32) external returns (uint256 rate) { 18 | uint256 add = (duty - 10**27) * (block.timestamp - rho); 19 | rate = vat.rate() + add; 20 | vat.fold(add); 21 | rho = block.timestamp; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/mocks/PoolUniV3Mock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | interface DepositorLike { 6 | function uniswapV3MintCallback(uint256, uint256, bytes calldata) external; 7 | } 8 | 9 | interface GemLike { 10 | function transfer(address, uint256) external; 11 | } 12 | 13 | contract PoolUniV3Mock { 14 | address public gem0; 15 | address public gem1; 16 | uint24 public fee; 17 | 18 | uint128 public random0; 19 | uint128 public random1; 20 | uint128 public random2; 21 | uint128 public random3; 22 | 23 | mapping (bytes32 => Position) public positions; 24 | 25 | struct Position { 26 | uint128 liquidity; 27 | uint256 feeGrowthInside0LastX128; 28 | uint256 feeGrowthInside1LastX128; 29 | uint128 tokensOwed0; 30 | uint128 tokensOwed1; 31 | } 32 | 33 | function mint(address, int24, int24, uint128, bytes calldata) external returns (uint128, uint128) { 34 | DepositorLike(msg.sender).uniswapV3MintCallback(random0, random1, abi.encode(gem0, gem1, fee)); 35 | 36 | return (random0, random1); 37 | } 38 | 39 | function burn(int24, int24, uint128) external view returns (uint128, uint128) { 40 | return (random0, random1); 41 | } 42 | 43 | function collect(address recipient, int24, int24, uint128 amt0R, uint128 amt1R) external returns (uint128, uint128) { 44 | uint128 col0 = amt0R > random2 ? random2 : amt0R; 45 | uint128 col1 = amt1R > random3 ? random3 : amt1R; 46 | GemLike(gem0).transfer(recipient, col0); 47 | GemLike(gem1).transfer(recipient, col1); 48 | return (col0, col1); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /test/mocks/PsmMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.16; 3 | 4 | interface GemLike { 5 | function approve(address, uint256) external; 6 | function transfer(address, uint256) external; 7 | function transferFrom(address, address, uint256) external; 8 | function decimals() external view returns (uint8); 9 | } 10 | 11 | contract PsmMock { 12 | mapping(address => uint256) public wards; 13 | 14 | address public immutable dai; 15 | address public immutable gem; 16 | uint256 public immutable to18ConversionFactor; 17 | 18 | event Rely(address indexed usr); 19 | event Deny(address indexed usr); 20 | event SellGem(address indexed owner, uint256 value, uint256 fee); 21 | event BuyGem(address indexed owner, uint256 value, uint256 fee); 22 | 23 | modifier auth() { 24 | require(wards[msg.sender] == 1, "PsmMock/not-authorized"); 25 | _; 26 | } 27 | 28 | constructor(address dai_, address gem_) { 29 | dai = dai_; 30 | gem = gem_; 31 | to18ConversionFactor = 10**(18 - GemLike(gem_).decimals()); 32 | 33 | wards[msg.sender] = 1; 34 | emit Rely(msg.sender); 35 | } 36 | 37 | function rely(address usr) external auth { 38 | wards[usr] = 1; 39 | emit Rely(usr); 40 | } 41 | 42 | function deny(address usr) external auth { 43 | wards[usr] = 0; 44 | emit Deny(usr); 45 | } 46 | 47 | function pocket() external view returns (address) { 48 | return address(this); 49 | } 50 | 51 | function sellGemNoFee(address usr, uint256 gemAmt) external auth returns (uint256 daiOutWad) { 52 | daiOutWad = gemAmt * to18ConversionFactor; 53 | 54 | GemLike(gem).transferFrom(msg.sender, address(this), gemAmt); 55 | GemLike(dai).transfer(usr, daiOutWad); 56 | 57 | emit SellGem(usr, gemAmt, 0); 58 | } 59 | 60 | function buyGemNoFee(address usr, uint256 gemAmt) external auth returns (uint256 daiInWad) { 61 | daiInWad = gemAmt * to18ConversionFactor; 62 | 63 | GemLike(dai).transferFrom(msg.sender, address(this), daiInWad); 64 | GemLike(gem).transfer(usr, gemAmt); 65 | 66 | emit BuyGem(usr, gemAmt, 0); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /test/mocks/RolesMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | contract RolesMock { 6 | bool ok; 7 | 8 | function setOk(bool ok_) external { 9 | ok = ok_; 10 | } 11 | 12 | function canCall(bytes32, address, address, bytes4) external view returns (bool) { 13 | return ok; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/mocks/UsdsJoinMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | import { VatMock } from "test/mocks/VatMock.sol"; 6 | import { GemMock } from "test/mocks/GemMock.sol"; 7 | 8 | contract UsdsJoinMock { 9 | VatMock public vat; 10 | GemMock public usds; 11 | 12 | constructor(VatMock vat_, GemMock usds_) { 13 | vat = vat_; 14 | usds = usds_; 15 | } 16 | 17 | function join(address usr, uint256 wad) external { 18 | vat.move(address(this), usr, wad * 10**27); 19 | usds.burn(msg.sender, wad); 20 | } 21 | 22 | function exit(address usr, uint256 wad) external { 23 | vat.move(msg.sender, address(this), wad * 10**27); 24 | usds.mint(usr, wad); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /test/mocks/UsdsMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | contract UsdsMock { 6 | mapping (address => uint256) public balanceOf; 7 | mapping (address => mapping (address => uint256)) public allowance; 8 | 9 | uint256 public totalSupply; 10 | 11 | constructor(uint256 initialSupply) { 12 | mint(msg.sender, initialSupply); 13 | } 14 | 15 | function approve(address spender, uint256 value) external returns (bool) { 16 | allowance[msg.sender][spender] = value; 17 | return true; 18 | } 19 | 20 | function transfer(address to, uint256 value) external returns (bool) { 21 | uint256 balance = balanceOf[msg.sender]; 22 | require(balance >= value, "Usds/insufficient-balance"); 23 | 24 | unchecked { 25 | balanceOf[msg.sender] = balance - value; 26 | balanceOf[to] += value; 27 | } 28 | return true; 29 | } 30 | 31 | function transferFrom(address from, address to, uint256 value) external returns (bool) { 32 | uint256 balance = balanceOf[from]; 33 | require(balance >= value, "Usds/insufficient-balance"); 34 | 35 | if (from != msg.sender) { 36 | uint256 allowed = allowance[from][msg.sender]; 37 | if (allowed != type(uint256).max) { 38 | require(allowed >= value, "Usds/insufficient-allowance"); 39 | 40 | unchecked { 41 | allowance[from][msg.sender] = allowed - value; 42 | } 43 | } 44 | } 45 | 46 | unchecked { 47 | balanceOf[from] = balance - value; 48 | balanceOf[to] += value; 49 | } 50 | return true; 51 | } 52 | 53 | function mint(address to, uint256 value) public { 54 | unchecked { 55 | balanceOf[to] = balanceOf[to] + value; 56 | } 57 | totalSupply = totalSupply + value; 58 | } 59 | 60 | function burn(address from, uint256 value) external { 61 | uint256 balance = balanceOf[from]; 62 | require(balance >= value, "Usds/insufficient-balance"); 63 | 64 | if (from != msg.sender) { 65 | uint256 allowed = allowance[from][msg.sender]; 66 | if (allowed != type(uint256).max) { 67 | require(allowed >= value, "Usds/insufficient-allowance"); 68 | 69 | unchecked { 70 | allowance[from][msg.sender] = allowed - value; 71 | } 72 | } 73 | } 74 | 75 | unchecked { 76 | balanceOf[from] = balance - value; 77 | totalSupply = totalSupply - value; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /test/mocks/VatMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | 3 | pragma solidity ^0.8.16; 4 | 5 | contract VatMock { 6 | uint256 public Art; 7 | uint256 public rate = 10**27; 8 | uint256 public line = 20_000_000 * 10**45; 9 | 10 | struct Urn { 11 | uint256 ink; 12 | uint256 art; 13 | } 14 | 15 | mapping (address => mapping (address => uint256)) public can; 16 | mapping (bytes32 => mapping (address => Urn )) public urns; 17 | mapping (bytes32 => mapping (address => uint)) public gem; 18 | mapping (address => uint256) public dai; 19 | 20 | function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256) { 21 | return (Art, rate, 0, line, 0); 22 | } 23 | 24 | function hope(address usr) external { 25 | can[msg.sender][usr] = 1; 26 | } 27 | 28 | function frob(bytes32 i, address u, address v, address w, int256 dink, int256 dart) external { 29 | require(u == msg.sender || can[u][msg.sender] == 1); 30 | Urn memory urn = urns[i][u]; 31 | 32 | urn.ink = dink >= 0 ? urn.ink + uint256(dink) : urn.ink - uint256(-dink); 33 | Art = urn.art = dart >= 0 ? urn.art + uint256(dart) : urn.art - uint256(-dart); 34 | 35 | gem[i][v] = dink >= 0 ? gem[i][v] - uint256(dink) : gem[i][v] + uint256(-dink); 36 | require(dart == 0 || rate <= uint256(type(int256).max)); 37 | int256 dtab = int256(rate) * dart; 38 | dai[w] = dtab >= 0 ? dai[w] + uint256(dtab) : dai[w] - uint256(-dtab); 39 | 40 | urns[i][u] = urn; 41 | } 42 | 43 | function move(address src, address dst, uint256 rad) external { 44 | require(src == msg.sender || can[src][msg.sender] == 1); 45 | dai[src] = dai[src] - rad; 46 | dai[dst] = dai[dst] + rad; 47 | } 48 | 49 | function slip(bytes32 ilk, address usr, int256 wad) external { 50 | gem[ilk][usr] = wad >= 0 ? gem[ilk][usr] + uint256(wad) : gem[ilk][usr] - uint256(-wad); 51 | } 52 | 53 | function grab(bytes32 i, address u, address v, address, int dink, int dart) external { 54 | Urn storage urn = urns[i][u]; 55 | 56 | urn.ink = dink >= 0 ? urn.ink + uint256(dink) : urn.ink - uint256(-dink); 57 | urn.art = dart >= 0 ? urn.art + uint256(dart) : urn.art - uint256(-dart); 58 | Art = dart >= 0 ? Art + uint256(dart) : Art - uint256(-dart); 59 | gem[i][v] = dink >= 0 ? gem[i][v] - uint256(dink) : gem[i][v] + uint256(-dink); 60 | } 61 | 62 | function fold(uint256 rate_) external { 63 | rate = rate + rate_; 64 | } 65 | } 66 | --------------------------------------------------------------------------------