Skip to content
Verified contractPartialUNLICENSED

TokenPortal

Address0xe2b92ac0bd9fb204b29fd367a59a8de9748daff3
Balance

0 ETH

 

Transactions

25

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
No
EVM version
prague
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,581,036
Creation transaction
0xb1476a8232…16da6c69a9

91 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/TokenPortal.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.27;

import {IERC20} from "@oz/token/ERC20/IERC20.sol";
import {SafeERC20} from "@oz/token/ERC20/utils/SafeERC20.sol";
import {ECDSA} from "@oz/utils/cryptography/ECDSA.sol";
import {Pausable} from "@oz/utils/Pausable.sol";
import {ReentrancyGuard} from "@oz/utils/ReentrancyGuard.sol";
import {Ownable2Step, Ownable} from "@oz/access/Ownable2Step.sol";

// Aztec Messaging Interfaces
import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol";
import {IInbox} from "@aztec/core/interfaces/messagebridge/IInbox.sol";
import {IOutbox} from "@aztec/core/interfaces/messagebridge/IOutbox.sol";
import {IRollup} from "@aztec/core/interfaces/IRollup.sol";
import {DataStructures} from "@aztec/core/libraries/DataStructures.sol";
import {Hash} from "@aztec/core/libraries/crypto/Hash.sol";
import {Epoch} from "@aztec/core/libraries/TimeLib.sol";

// =============================================================
// CUSTOM ERRORS
// =============================================================

error AlreadyInitialized();
error InvalidAddress();
error FeeTooHigh();
error NoFeesToWithdraw();
error InvalidVerification();
error PassportNonceUsed();
error CleanHandsNonceUsed();
error InvalidPassportSignature();
error AmountExceedsLimit();
error Unauthorized();
error NoPendingOwner();
error NotTrustedForwarder();
error DepositsPaused();

/**
 * @title TokenPortal
 * @dev Manages L1/L2 token transfers between Ethereum and Aztec with fee logic and attestation checks.
 */
contract TokenPortal is Pausable, ReentrancyGuard, Ownable2Step {
    using SafeERC20 for IERC20;

    // =============================================================
    // DATA STRUCTURES
    // =============================================================

    struct PassportData {
        uint256 maxAmount;
        uint256 nonce;
        uint256 deadline;
        bytes signature;
    }

    struct CleanHandsData {
        uint256 nonce;
        bytes signature;
    }

    // =============================================================
    // STATE VARIABLES
    // =============================================================

    address private immutable DEPLOYER;

    // Aztec Infrastructure
    IRegistry public registry;
    IERC20 public underlying;
    IRollup public rollup;
    IOutbox public outbox;
    IInbox public inbox;
    bytes32 public l2Bridge;
    uint256 public rollupVersion;
    // Attestation Config
    address public humanIdAttester;
    uint256 public cleanHandsCircuitId;
    uint256 public cleanHandsActionId;
    address public passportSigner;

    mapping(address => mapping(uint256 => bool)) public passportNonces;
    mapping(address => mapping(uint256 => bool)) public cleanHandsNonces;

    // Trusted Forwarders (for relaying private deposits)
    mapping(address => bool) public trustedForwarders;

    // Fee Management
    uint256 public feeBasisPoints;
    uint256 public constant MAX_FEE_BASIS_POINTS = 1000; // 10%
    address public feeRecipient;
    uint256 public collectedFees;

    // Migration pause: blocks new deposits while allowing withdrawals during rollup upgrade window
    bool public depositsActive = true;

    // =============================================================
    // EVENTS
    // =============================================================

    event Initialized(address indexed registry, address indexed underlying, bytes32 l2Bridge);
    event DepositToAztecPublic(
        bytes32 indexed to, uint256 amount, uint256 fee, bytes32 secretHash, bytes32 key, uint256 index
    );
    event DepositToAztecPrivate(uint256 amount, uint256 fee, bytes32 secretHash, bytes32 key, uint256 index);
    event FeeUpdated(uint256 newFeeBasisPoints);
    event FeeRecipientUpdated(address indexed newFeeRecipient);
    event FeesWithdrawn(address indexed recipient, uint256 amount);
    event TokensRescued(address indexed token, address indexed to, uint256 amount);
    event AttestationConfigUpdated(address indexed attester, uint256 circuitId, uint256 actionId, address indexed signer);
    event TrustedForwarderUpdated(address indexed forwarder, bool trusted);
    event DepositsBlocked();
    event DepositsUnblocked();
    event OwnershipTransferProposed(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferCancelled(address indexed currentOwner);
    // =============================================================
    // CONSTRUCTOR / INITIALIZER
    // =============================================================

    constructor(
        address _initialOwner,
        address _feeRecipient,
        uint256 _feeBasisPoints,
        address _humanIdAttester,
        uint256 _cleanHandsCircuitId,
        uint256 _cleanHandsActionId,
        address _passportSigner
    ) Ownable(_initialOwner) {
        DEPLOYER = _msgSender();

        if (_feeRecipient == address(0)) revert InvalidAddress();
        if (_feeBasisPoints > MAX_FEE_BASIS_POINTS) revert FeeTooHigh();

        feeRecipient = _feeRecipient;
        feeBasisPoints = _feeBasisPoints;
        if (_humanIdAttester == address(0)) revert InvalidAddress();
        if (_passportSigner == address(0)) revert InvalidAddress();
        humanIdAttester = _humanIdAttester;
        cleanHandsCircuitId = _cleanHandsCircuitId;
        cleanHandsActionId = _cleanHandsActionId;
        passportSigner = _passportSigner;
    }

    function initialize(address _registry, address _underlying, bytes32 _l2Bridge) external {
        if (_msgSender() != DEPLOYER) revert Unauthorized();
        if (address(registry) != address(0)) revert AlreadyInitialized();
        if (_registry == address(0) || _underlying == address(0) || _l2Bridge == bytes32(0)) {
            revert InvalidAddress();
        }

        registry = IRegistry(_registry);
        underlying = IERC20(_underlying);
        l2Bridge = _l2Bridge;

        rollup = IRollup(address(registry.getCanonicalRollup()));
        outbox = rollup.getOutbox();
        inbox = rollup.getInbox();
        rollupVersion = rollup.getVersion();

        emit Initialized(_registry, _underlying, _l2Bridge);
    }

    // =============================================================
    // EXTERNAL FUNCTIONS: USER ACTIONS
    // =============================================================

    function depositToAztecPublic(
        bytes32 _to,
        uint256 _amount,
        bytes32 _secretHash,
        CleanHandsData calldata _cleanHands,
        PassportData calldata _passport
    ) external whenNotPaused nonReentrant returns (bytes32, uint256, uint256) {
        if (!depositsActive) revert DepositsPaused();
        require(_amount > 0, "Amount must be greater than zero");
        _validateAttestations(_msgSender(), _amount, _cleanHands, _passport);

        uint256 fee = calculateFee(_amount);
        uint256 amountAfterFee = _amount - fee;

        DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion);
        bytes32 contentHash =
            Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", _to, amountAfterFee));

        underlying.safeTransferFrom(_msgSender(), address(this), _amount);
        collectedFees += fee;

        (bytes32 key, uint256 index) = inbox.sendL2Message(actor, contentHash, _secretHash);

        emit DepositToAztecPublic(_to, amountAfterFee, fee, _secretHash, key, index);
        return (key, index, amountAfterFee);
    }

    function depositToAztecPublicFor(
        address _depositor,
        bytes32 _to,
        uint256 _amount,
        bytes32 _secretHash,
        CleanHandsData calldata _cleanHands,
        PassportData calldata _passport
    ) external whenNotPaused nonReentrant returns (bytes32, uint256, uint256) {
        if (!depositsActive) revert DepositsPaused();
        if (!trustedForwarders[msg.sender]) revert NotTrustedForwarder();
        require(_amount > 0, "Amount must be greater than zero");
        _validateAttestations(_depositor, _amount, _cleanHands, _passport);

        uint256 fee = calculateFee(_amount);
        uint256 amountAfterFee = _amount - fee;

        DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion);
        bytes32 contentHash =
            Hash.sha256ToField(abi.encodeWithSignature("mint_to_public(bytes32,uint256)", _to, amountAfterFee));

        underlying.safeTransferFrom(msg.sender, address(this), _amount);
        collectedFees += fee;

        (bytes32 key, uint256 index) = inbox.sendL2Message(actor, contentHash, _secretHash);

        emit DepositToAztecPublic(_to, amountAfterFee, fee, _secretHash, key, index);
        return (key, index, amountAfterFee);
    }

    function depositToAztecPrivate(
        uint256 _amount,
        bytes32 _secretHashForL2MessageConsumption,
        CleanHandsData calldata _cleanHands,
        PassportData calldata _passport
    ) external whenNotPaused nonReentrant returns (bytes32, uint256, uint256) {
        if (!depositsActive) revert DepositsPaused();
        require(_amount > 0, "Amount must be greater than zero");
        _validateAttestations(_msgSender(), _amount, _cleanHands, _passport);

        uint256 fee = calculateFee(_amount);
        uint256 amountAfterFee = _amount - fee;

        DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion);
        bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_private(uint256)", amountAfterFee));

        underlying.safeTransferFrom(_msgSender(), address(this), _amount);
        collectedFees += fee;

        (bytes32 key, uint256 index) = inbox.sendL2Message(actor, contentHash, _secretHashForL2MessageConsumption);

        emit DepositToAztecPrivate(amountAfterFee, fee, _secretHashForL2MessageConsumption, key, index);
        return (key, index, amountAfterFee);
    }

    function depositToAztecPrivateFor(
        address _depositor,
        uint256 _amount,
        bytes32 _secretHashForL2MessageConsumption,
        CleanHandsData calldata _cleanHands,
        PassportData calldata _passport
    ) external whenNotPaused nonReentrant returns (bytes32, uint256, uint256) {
        if (!depositsActive) revert DepositsPaused();
        if (!trustedForwarders[msg.sender]) revert NotTrustedForwarder();
        require(_amount > 0, "Amount must be greater than zero");
        _validateAttestations(_depositor, _amount, _cleanHands, _passport);

        uint256 fee = calculateFee(_amount);
        uint256 amountAfterFee = _amount - fee;

        DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion);
        bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_private(uint256)", amountAfterFee));

        underlying.safeTransferFrom(msg.sender, address(this), _amount);
        collectedFees += fee;

        (bytes32 key, uint256 index) = inbox.sendL2Message(actor, contentHash, _secretHashForL2MessageConsumption);

        emit DepositToAztecPrivate(amountAfterFee, fee, _secretHashForL2MessageConsumption, key, index);
        return (key, index, amountAfterFee);
    }

    function withdraw(
        address _recipient,
        uint256 _amount,
        bool _withCaller,
        Epoch _epoch,
        uint256 _numCheckpointsInEpoch,
        uint256 _leafIndex,
        bytes32[] calldata _path
    ) external whenNotPaused nonReentrant {
        require(_amount > 0, "Amount must be greater than zero");
        DataStructures.L2ToL1Msg memory message = DataStructures.L2ToL1Msg({
            sender: DataStructures.L2Actor(l2Bridge, rollupVersion),
            recipient: DataStructures.L1Actor(address(this), block.chainid),
            content: Hash.sha256ToField(
                abi.encodeWithSignature(
                    "withdraw(address,uint256,address)", _recipient, _amount, _withCaller ? _msgSender() : address(0)
                )
            )
        });

        uint256 fee = calculateFee(_amount);
        uint256 amountAfterFee = _amount - fee;
        collectedFees += fee;

        outbox.consume(message, _epoch, _numCheckpointsInEpoch, _leafIndex, _path);

        underlying.safeTransfer(_recipient, amountAfterFee);
    }

    // =============================================================
    // EXTERNAL FUNCTIONS: ADMIN
    // =============================================================

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Pause new deposits only. Withdrawals remain live.
    ///         Use during rollup upgrade delay window (migration pause).
    function pauseDeposits() external onlyOwner {
        depositsActive = false;
        emit DepositsBlocked();
    }

    /// @notice Re-enable deposits after migration is complete.
    function unpauseDeposits() external onlyOwner {
        depositsActive = true;
        emit DepositsUnblocked();
    }

    function setTrustedForwarder(address _forwarder, bool _trusted) external onlyOwner {
        if (_forwarder == address(0)) revert InvalidAddress();
        trustedForwarders[_forwarder] = _trusted;
        emit TrustedForwarderUpdated(_forwarder, _trusted);
    }

    function updateAttestationConfig(address _attester, uint256 _circuitId, uint256 _actionId, address _signer) external onlyOwner {
        if (_attester == address(0)) revert InvalidAddress();
        if (_signer == address(0)) revert InvalidAddress();
        humanIdAttester = _attester;
        cleanHandsCircuitId = _circuitId;
        cleanHandsActionId = _actionId;
        passportSigner = _signer;
        emit AttestationConfigUpdated(_attester, _circuitId, _actionId, _signer);
    }

    function updateFee(uint256 _newFeeBasisPoints) external onlyOwner {
        if (_newFeeBasisPoints > MAX_FEE_BASIS_POINTS) revert FeeTooHigh();
        feeBasisPoints = _newFeeBasisPoints;
        emit FeeUpdated(_newFeeBasisPoints);
    }

    function updateFeeRecipient(address _newFeeRecipient) external onlyOwner {
        if (_newFeeRecipient == address(0)) revert InvalidAddress();
        feeRecipient = _newFeeRecipient;
        emit FeeRecipientUpdated(_newFeeRecipient);
    }

    function withdrawFees() external onlyOwner nonReentrant {
        uint256 amount = collectedFees;
        if (amount == 0) revert NoFeesToWithdraw();

        collectedFees = 0;
        underlying.safeTransfer(feeRecipient, amount);
        emit FeesWithdrawn(feeRecipient, amount);
    }

    function rescueToken(address _token, uint256 _amount) external onlyOwner {
        if (_token == address(0)) revert InvalidAddress();
        IERC20(_token).safeTransfer(owner(), _amount);
        emit TokensRescued(_token, owner(), _amount);
    }

    // =============================================================
    // INTERNAL HELPERS
    // =============================================================

    function _validateAttestations(
        address _depositor,
        uint256 _amount,
        CleanHandsData calldata _cleanHands,
        PassportData calldata _passport
    ) internal {
        bool verified = false;

        // 1. Try Clean Hands Verification
        if (_cleanHands.signature.length > 0) {
            if (cleanHandsNonces[_depositor][_cleanHands.nonce]) {
                revert CleanHandsNonceUsed();
            }
            verified = _verifyCleanHandsSignatureFor(
                _depositor, _cleanHands.nonce, cleanHandsCircuitId, cleanHandsActionId, _cleanHands.signature
            );
            cleanHandsNonces[_depositor][_cleanHands.nonce] = true;
        }

        // 2. Fallback to Passport Verification
        if (!verified) {
            if (_passport.signature.length == 0) revert InvalidVerification();
            if (passportNonces[_depositor][_passport.nonce]) {
                revert PassportNonceUsed();
            }
            if (
                !_verifyPassportSignatureFor(
                    _depositor, _passport.maxAmount, _passport.nonce, _passport.deadline, _passport.signature
                )
            ) {
                revert InvalidPassportSignature();
            }
            if (_amount > _passport.maxAmount) revert AmountExceedsLimit();

            passportNonces[_depositor][_passport.nonce] = true;
        }
    }

    function verifyCleanHandsSignature(
        uint256 nonce,
        bytes memory signature
    ) public view returns (bool) {
        return _verifyCleanHandsSignatureFor(_msgSender(), nonce, cleanHandsCircuitId, cleanHandsActionId, signature);
    }

    function _verifyCleanHandsSignatureFor(
        address _depositor,
        uint256 nonce,
        uint256 circuitId,
        uint256 actionId,
        bytes memory signature
    ) internal view returns (bool) {
        bytes32 digest = keccak256(abi.encodePacked(nonce, circuitId, actionId, _depositor));
        bytes32 personalSignPreimage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", digest));
        address recovered = ECDSA.recover(personalSignPreimage, signature);

        return recovered == humanIdAttester;
    }

    function verifyPassportSignature(uint256 maxAmount, uint256 nonce, uint256 deadline, bytes memory signature)
        public
        view
        returns (bool)
    {
        return _verifyPassportSignatureFor(_msgSender(), maxAmount, nonce, deadline, signature);
    }

    function _verifyPassportSignatureFor(
        address _depositor,
        uint256 maxAmount,
        uint256 nonce,
        uint256 deadline,
        bytes memory signature
    ) internal view returns (bool) {
        if (block.timestamp > deadline) return false;
        bytes32 messageHash = keccak256(abi.encodePacked(_depositor, maxAmount, nonce, deadline, address(this)));
        bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));

        address recovered = ECDSA.recover(ethSignedMessageHash, signature);

        return recovered == passportSigner;
    }

    function calculateFee(uint256 _amount) public view returns (uint256) {
        return (_amount * feeBasisPoints) / 10000;
    }

    function getCollectedFees() external view returns (uint256) {
        return collectedFees;
    }

    function getFeeRecipient() external view returns (address) {
        return feeRecipient;
    }

    // =============================================================
    // OWNERSHIP 2-STEP (CUSTOM OVERRIDES)
    // =============================================================

    function proposeOwnershipTransfer(address newOwner) public onlyOwner {
        if (newOwner == address(0)) revert InvalidAddress();

        address previousOwner = owner();
        // this is the main function that goes through the 2-step process
        transferOwnership(newOwner); // This sets pendingOwner, requires acceptOwnership() to complete
        emit OwnershipTransferProposed(previousOwner, newOwner);
    }

    function cancelOwnershipTransfer() public onlyOwner {
        address pendingOwnerAddress = pendingOwner();
        if (pendingOwnerAddress == address(0)) revert NoPendingOwner();

        // Cancel by transferring ownership back to current owner (self)
        // this is the internal function that directly transfers the ownership BYPASSING the 2-step process
        _transferOwnership(owner());
        emit OwnershipTransferCancelled(owner());
    }

    function acceptOwnership() public override {
        super.acceptOwnership();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "evmVersion": "prague",
  "remappings": [
    "@oz/=lib/openzeppelin-contracts/contracts/",
    "@aztec/=lib/aztec-contracts/l1-contracts/src/",
    "@aztec-blob-lib/=lib/aztec-contracts/l1-contracts/src/core/libraries/rollup/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@test/=test/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "aztec-contracts/=lib/aztec-contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.