-
-
Notifications
You must be signed in to change notification settings - Fork 89
feat: Add token transformation tracking system for DeFi protocol interactions #156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
hanzel98
wants to merge
6
commits into
main
Choose a base branch
from
feat/token-transformation-system
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
fb03cbe
feat: Add token transformation tracking system for DeFi protocol inte…
hanzel98 ab9c08d
docs: Update TokenTransformationSystem documentation
hanzel98 8be2401
Remove actionHash parameter from AdapterManager and update event to l…
hanzel98 4066cf6
refactor: extract Aave interfaces into IAave.sol
hanzel98 b761744
docs: combine TokenTransformation docs into single comprehensive docu…
hanzel98 777fa5a
docs: clarify diagram note in TokenTransformationSystem
hanzel98 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| // SPDX-License-Identifier: MIT AND Apache-2.0 | ||
| pragma solidity 0.8.23; | ||
|
|
||
| import "forge-std/Script.sol"; | ||
| import { console2 } from "forge-std/console2.sol"; | ||
|
|
||
| import { IDelegationManager } from "../src/interfaces/IDelegationManager.sol"; | ||
| import { TokenTransformationEnforcer } from "../src/enforcers/TokenTransformationEnforcer.sol"; | ||
| import { AdapterManager } from "../src/helpers/adapters/AdapterManager.sol"; | ||
|
|
||
| /** | ||
| * @title DeployTokenTransformationSystem | ||
| * @notice Deploys TokenTransformationEnforcer and AdapterManager together | ||
| * @dev Resolves circular dependency by deploying in correct order: | ||
| * 1. Deploy AdapterManager first (no enforcer in constructor) | ||
| * 2. Deploy TokenTransformationEnforcer with AdapterManager address | ||
| * 3. Owner sets enforcer in AdapterManager | ||
| * @dev Run the script with: | ||
| * forge script script/DeployTokenTransformationSystem.s.sol --rpc-url <your_rpc_url> --private-key $PRIVATE_KEY --broadcast | ||
| */ | ||
| contract DeployTokenTransformationSystem is Script { | ||
| bytes32 salt; | ||
| IDelegationManager delegationManager; | ||
| address owner; | ||
| address deployer; | ||
|
|
||
| function setUp() public { | ||
| salt = bytes32(abi.encodePacked(vm.envString("SALT"))); | ||
| delegationManager = IDelegationManager(vm.envAddress("DELEGATION_MANAGER_ADDRESS")); | ||
| owner = vm.envAddress("OWNER_ADDRESS"); | ||
| deployer = msg.sender; | ||
|
|
||
| console2.log("~~~"); | ||
| console2.log("Deployer: %s", address(deployer)); | ||
| console2.log("Owner: %s", address(owner)); | ||
| console2.log("DelegationManager: %s", address(delegationManager)); | ||
| console2.log("Salt:"); | ||
| console2.logBytes32(salt); | ||
| } | ||
|
|
||
| function run() public { | ||
| console2.log("~~~"); | ||
| console2.log("Deploying Token Transformation System..."); | ||
| vm.startBroadcast(); | ||
|
|
||
| // Step 1: Deploy AdapterManager first (no enforcer in constructor) | ||
| address adapterManager = address(new AdapterManager{ salt: salt }(owner, delegationManager)); | ||
| console2.log("AdapterManager: %s", adapterManager); | ||
|
|
||
| // Step 2: Deploy TokenTransformationEnforcer with the real AdapterManager address | ||
| address tokenTransformationEnforcer = address(new TokenTransformationEnforcer{ salt: salt }(adapterManager)); | ||
| console2.log("TokenTransformationEnforcer: %s", tokenTransformationEnforcer); | ||
|
|
||
| vm.stopBroadcast(); | ||
|
|
||
| // Step 3: Set the enforcer in AdapterManager (as owner) | ||
| // If deployer is the owner, set it now. Otherwise, owner must call setTokenTransformationEnforcer separately | ||
| if (deployer == owner) { | ||
| vm.startBroadcast(); | ||
| AdapterManager(payable(adapterManager)) | ||
| .setTokenTransformationEnforcer(TokenTransformationEnforcer(tokenTransformationEnforcer)); | ||
| vm.stopBroadcast(); | ||
| console2.log("Enforcer set in AdapterManager"); | ||
| } else { | ||
| console2.log("WARNING: Deployer is not the owner."); | ||
| console2.log("Owner must call setTokenTransformationEnforcer separately:"); | ||
| console2.log( | ||
| " AdapterManager(%s).setTokenTransformationEnforcer(TokenTransformationEnforcer(%s))", | ||
| adapterManager, | ||
| tokenTransformationEnforcer | ||
| ); | ||
| } | ||
|
|
||
| // Step 4: Verify the deployment (read-only, no broadcast needed) | ||
| require( | ||
| TokenTransformationEnforcer(tokenTransformationEnforcer).adapterManager() == adapterManager, | ||
| "DeployTokenTransformationSystem: enforcer adapterManager mismatch" | ||
| ); | ||
| if (deployer == owner) { | ||
| require( | ||
| address(AdapterManager(payable(adapterManager)).tokenTransformationEnforcer()) == tokenTransformationEnforcer, | ||
| "DeployTokenTransformationSystem: adapterManager enforcer mismatch" | ||
| ); | ||
| console2.log("Deployment verified successfully"); | ||
| } else { | ||
| console2.log("Note: Enforcer not yet set. Verification will pass after owner calls setTokenTransformationEnforcer."); | ||
| } | ||
|
|
||
| console2.log("~~~"); | ||
| console2.log("Token Transformation System deployed successfully!"); | ||
| console2.log("AdapterManager: %s", adapterManager); | ||
| console2.log("TokenTransformationEnforcer: %s", tokenTransformationEnforcer); | ||
| } | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,248 @@ | ||
| // SPDX-License-Identifier: MIT AND Apache-2.0 | ||
| pragma solidity 0.8.23; | ||
|
|
||
| import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; | ||
| import { ExecutionLib } from "@erc7579/lib/ExecutionLib.sol"; | ||
|
|
||
| import { CaveatEnforcer } from "./CaveatEnforcer.sol"; | ||
| import { ModeCode } from "../utils/Types.sol"; | ||
|
|
||
| /** | ||
| * @title TokenTransformationEnforcer | ||
| * @notice Tracks token transformations through protocol interactions (e.g., lending protocols). | ||
| * @dev This enforcer allows tracking multiple tokens per delegationHash, enabling delegation | ||
| * of an initial token amount and tracking what it transforms into through protocol interactions. | ||
| * @dev The enforcer validates that token usage doesn't exceed tracked amounts. | ||
| * @dev State updates can only be made by the AdapterManager. | ||
| */ | ||
| contract TokenTransformationEnforcer is CaveatEnforcer { | ||
| using ExecutionLib for bytes; | ||
|
|
||
| ////////////////////////////// State ////////////////////////////// | ||
|
|
||
| /// @dev Mapping from delegationHash => token => available amount | ||
| mapping(bytes32 delegationHash => mapping(address token => uint256 amount)) public availableAmounts; | ||
|
|
||
| /// @dev Mapping to track if initial token has been initialized for a delegationHash | ||
| mapping(bytes32 delegationHash => bool initialized) public isInitialized; | ||
|
|
||
| /// @dev Address of the AdapterManager that can update state | ||
| address public immutable adapterManager; | ||
|
|
||
| ////////////////////////////// Events ////////////////////////////// | ||
|
|
||
| /// @dev Emitted when asset state is updated for a delegation | ||
| event AssetStateUpdated(bytes32 indexed delegationHash, address indexed token, uint256 oldAmount, uint256 newAmount); | ||
|
|
||
| /// @dev Emitted when tokens are spent from a delegation | ||
| event TokensSpent(bytes32 indexed delegationHash, address indexed token, uint256 amount, uint256 remaining); | ||
|
|
||
| ////////////////////////////// Errors ////////////////////////////// | ||
|
|
||
| /// @dev Error thrown when caller is not the AdapterManager | ||
| error NotAdapterManager(); | ||
|
|
||
| /// @dev Error thrown when insufficient tokens are available | ||
| error InsufficientTokensAvailable(bytes32 delegationHash, address token, uint256 requested, uint256 available); | ||
|
|
||
| /// @dev Error thrown when invalid terms length is provided | ||
| error InvalidTermsLength(); | ||
|
|
||
| /// @dev Error thrown when protocol is not allowed | ||
| error ProtocolNotAllowed(address protocol); | ||
|
|
||
| ////////////////////////////// Constructor ////////////////////////////// | ||
|
|
||
| /** | ||
| * @notice Initializes the TokenTransformationEnforcer | ||
| * @param _adapterManager Address of the AdapterManager contract | ||
| */ | ||
| constructor(address _adapterManager) { | ||
| if (_adapterManager == address(0)) revert("TokenTransformationEnforcer:invalid-adapter-manager"); | ||
| adapterManager = _adapterManager; | ||
| } | ||
|
|
||
| ////////////////////////////// Modifiers ////////////////////////////// | ||
|
|
||
| modifier onlyAdapterManager() { | ||
| if (msg.sender != adapterManager) revert NotAdapterManager(); | ||
| _; | ||
| } | ||
|
|
||
| ////////////////////////////// Public Methods ////////////////////////////// | ||
|
|
||
| /** | ||
| * @notice Validates that the requested token amount is available for the delegation | ||
| * @dev Expected delegation types: | ||
| * - Initial delegation: Grants access to an initial token amount (e.g., 1000 USDC) | ||
| * - Protocol interaction delegations: Used with AdapterManager to track token transformations | ||
| * through lending protocols (e.g., USDC -> aUSDC via Aave deposit) | ||
| * - Multi-token delegations: Tracks multiple tokens per delegationHash as tokens are transformed | ||
| * @dev When used with AdapterManager, _args must contain the protocol address (20 bytes) | ||
| * and the protocol will be validated against allowedProtocols from terms | ||
| * @param _terms Encoded initial token address and amount (52 bytes: 20 bytes token + 32 bytes amount) | ||
| * Extended format may include allowed protocol addresses | ||
| * @param _args Protocol address (20 bytes) when used with AdapterManager, empty otherwise | ||
| * @param _mode The execution mode (must be Single callType, Default execType) | ||
| * @param _executionCallData The execution call data containing the transfer | ||
| * @param _delegationHash The hash of the delegation | ||
| */ | ||
| function beforeHook( | ||
| bytes calldata _terms, | ||
| bytes calldata _args, | ||
| ModeCode _mode, | ||
| bytes calldata _executionCallData, | ||
| bytes32 _delegationHash, | ||
| address, | ||
| address | ||
| ) | ||
| public | ||
| override | ||
| onlySingleCallTypeMode(_mode) | ||
| onlyDefaultExecutionMode(_mode) | ||
| { | ||
| (address initialToken_, uint256 initialAmount_, address[] memory allowedProtocols_) = getTermsInfo(_terms); | ||
| _validateProtocol(_args, allowedProtocols_); | ||
|
|
||
| (address token_,, bytes calldata callData_) = _executionCallData.decodeSingle(); | ||
|
|
||
| // Validate that this is an ERC20 transfer | ||
| require(callData_.length == 68, "TokenTransformationEnforcer:invalid-execution-length"); | ||
| require(bytes4(callData_[0:4]) == IERC20.transfer.selector, "TokenTransformationEnforcer:invalid-method"); | ||
|
|
||
| // Decode transfer amount | ||
| uint256 transferAmount_ = uint256(bytes32(callData_[36:68])); | ||
|
|
||
| // Get available amount | ||
| uint256 available_ = availableAmounts[_delegationHash][token_]; | ||
|
|
||
| // Initialize from terms only if this is the first use of the initial token | ||
| // Only initialize if: token matches initial token AND delegationHash hasn't been initialized yet | ||
| if (available_ == 0 && !isInitialized[_delegationHash] && token_ == initialToken_) { | ||
| availableAmounts[_delegationHash][token_] = initialAmount_; | ||
| isInitialized[_delegationHash] = true; | ||
| available_ = initialAmount_; | ||
| } | ||
|
|
||
| if (transferAmount_ > available_) { | ||
| revert InsufficientTokensAvailable(_delegationHash, token_, transferAmount_, available_); | ||
| } | ||
|
|
||
| // Deduct from available amount | ||
| availableAmounts[_delegationHash][token_] = available_ - transferAmount_; | ||
|
|
||
| emit TokensSpent(_delegationHash, token_, transferAmount_, available_ - transferAmount_); | ||
| } | ||
|
|
||
| ////////////////////////////// Private/Internal Methods ////////////////////////////// | ||
|
|
||
| /** | ||
| * @notice Validates that a protocol address from args is allowed according to the allowedProtocols list | ||
| * @param _args Protocol address (20 bytes) when used with AdapterManager, empty otherwise | ||
| * @param _allowedProtocols Array of allowed protocol addresses from terms | ||
| */ | ||
| function _validateProtocol(bytes calldata _args, address[] memory _allowedProtocols) internal pure { | ||
| // If args is empty, no protocol validation needed (backward compatible) | ||
| // TODO: Validate if this is secure | ||
| if (_args.length == 0) { | ||
| return; | ||
| } | ||
|
|
||
| // If args is provided, it must be exactly 20 bytes (protocol address) | ||
| if (_args.length != 20) revert InvalidTermsLength(); | ||
| address protocol_ = address(bytes20(_args[:20])); | ||
|
|
||
| // Validate protocol against allowed list | ||
| if (_allowedProtocols.length > 0) { | ||
| bool isAllowed_ = false; | ||
| for (uint256 i = 0; i < _allowedProtocols.length; i++) { | ||
| if (_allowedProtocols[i] == protocol_) { | ||
| isAllowed_ = true; | ||
| break; | ||
| } | ||
| } | ||
| if (!isAllowed_) { | ||
| revert ProtocolNotAllowed(protocol_); | ||
| } | ||
| } | ||
| // If no protocols specified in terms, allow all (backward compatible) | ||
| } | ||
|
|
||
| ////////////////////////////// Public Methods ////////////////////////////// | ||
|
|
||
| /** | ||
| * @notice Updates the asset state for a delegation after a protocol interaction | ||
| * @dev Only callable by the AdapterManager | ||
| * @param _delegationHash The hash of the delegation | ||
| * @param _token The token address | ||
| * @param _amount The new amount available (adds to existing if token already tracked) | ||
| */ | ||
| function updateAssetState(bytes32 _delegationHash, address _token, uint256 _amount) external onlyAdapterManager { | ||
| uint256 oldAmount_ = availableAmounts[_delegationHash][_token]; | ||
| uint256 newAmount_ = oldAmount_ + _amount; | ||
| availableAmounts[_delegationHash][_token] = newAmount_; | ||
|
|
||
| emit AssetStateUpdated(_delegationHash, _token, oldAmount_, newAmount_); | ||
| } | ||
|
|
||
| /** | ||
| * @notice Gets the available amount for a specific token in a delegation | ||
| * @param _delegationHash The hash of the delegation | ||
| * @param _token The token address | ||
| * @return The available amount | ||
| */ | ||
| function getAvailableAmount(bytes32 _delegationHash, address _token) external view returns (uint256) { | ||
| return availableAmounts[_delegationHash][_token]; | ||
| } | ||
|
|
||
| /** | ||
| * @notice Decodes the terms used in this CaveatEnforcer | ||
| * @dev Terms format: | ||
| * - Base (52 bytes): 20 bytes token address + 32 bytes initial amount | ||
| * - Extended (optional): 1 byte protocol count + N * 20 bytes protocol addresses | ||
| * - Minimum length: 52 bytes (no protocols, backward compatible) | ||
| * - Maximum length: 52 + 1 + (255 * 20) = 5162 bytes | ||
| * @param _terms Encoded data | ||
| * @return token_ The initial token address | ||
| * @return amount_ The initial amount | ||
| * @return allowedProtocols_ Array of allowed protocol addresses (empty if none specified) | ||
| */ | ||
| function getTermsInfo(bytes calldata _terms) | ||
| public | ||
| pure | ||
| returns (address token_, uint256 amount_, address[] memory allowedProtocols_) | ||
| { | ||
| if (_terms.length < 52) revert InvalidTermsLength(); | ||
|
|
||
| token_ = address(bytes20(_terms[:20])); | ||
| amount_ = uint256(bytes32(_terms[20:52])); | ||
|
|
||
| // Check if protocols are specified | ||
| if (_terms.length == 52) { | ||
| // No protocols specified (backward compatible) | ||
| allowedProtocols_ = new address[](0); | ||
| } else { | ||
| // Must have at least 53 bytes (base + count byte) | ||
| if (_terms.length < 53) revert InvalidTermsLength(); | ||
|
|
||
| uint8 protocolCount_ = uint8(_terms[52]); | ||
|
|
||
| // Expected length: 52 (base) + 1 (count) + protocolCount * 20 (addresses) | ||
| uint256 expectedLength_ = 53 + (protocolCount_ * 20); | ||
| if (_terms.length != expectedLength_) { | ||
| revert InvalidTermsLength(); | ||
| } | ||
|
|
||
| if (protocolCount_ == 0) { | ||
| allowedProtocols_ = new address[](0); | ||
| } else { | ||
| allowedProtocols_ = new address[](protocolCount_); | ||
| for (uint8 i = 0; i < protocolCount_; i++) { | ||
| uint256 offset_ = 53 + (i * 20); | ||
| allowedProtocols_[i] = address(bytes20(_terms[offset_:offset_ + 20])); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
save a couple units gas by caching new amount vs subtracting twice