Skip to content
Verified contractExactApache-2.0

TokenPortal

Address0x2ab479ba9d6997eaea5c83aea8ceafbbb25d254f
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.30

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
Apache-2.0
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,330,507
Creation transaction
0x8add891fd7…dbf94a2367
Main copy (most transactions)
0x32548cfb…9a542a73

97 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: Apache-2.0
pragma solidity ^0.8.28;

import {IRollup} from "@aztec/core/interfaces/IRollup.sol";
import {IInbox} from "@aztec/core/interfaces/messagebridge/IInbox.sol";
import {IOutbox} from "@aztec/core/interfaces/messagebridge/IOutbox.sol";
import {Hash} from "@aztec/core/libraries/crypto/Hash.sol";
import {DataStructures} from "@aztec/core/libraries/DataStructures.sol";
import {IRegistry} from "@aztec/governance/interfaces/IRegistry.sol";
import {Ownable} from "@oz/access/Ownable.sol";
import {IERC20} from "@oz/interfaces/IERC20.sol";
import {SafeERC20} from "@oz/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "@oz/utils/structs/EnumerableSet.sol";
import {ISignatureTransfer} from "@permit2/interfaces/ISignatureTransfer.sol";
import {ICapacityProvider} from "./interfaces/ICapacityProvider.sol";
import {ITokenPortal} from "./interfaces/ITokenPortal.sol";
import {ITokenUtilizationMeter} from "./interfaces/ITokenUtilization.sol";
import {OutboxUtils, OutboxMessageMetadata} from "./libraries/OutboxUtils.sol";

/// @title Token Portal
/// @author Nyx.money
/// @notice Portal contract for bridging an ERC20 token to Aztec
/// @dev Originally forked from https://github.com/AztecProtocol/aztec-packages/blob/v1.1.2/l1-contracts/test/portals/TokenPortal.sol
contract TokenPortal is ITokenPortal, Ownable {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;
    using OutboxUtils for IOutbox;
    using OutboxUtils for OutboxMessageMetadata;

    /// @notice The Aztec registry this portal is bound to
    IRegistry public immutable REGISTRY;

    /// @notice The Permit2 contract for permit-based token transfers
    ISignatureTransfer public immutable PERMIT2;

    IERC20 private immutable _UNDERLYING;

    /// @inheritdoc ITokenPortal
    IRollup public rollup;

    /// @notice Aztec rollup version
    uint256 public rollupVersion;

    /// @notice Aztec outbox for L2 -> L1 messages
    IOutbox public outbox;

    /// @notice Aztec inbox for L1 -> L2 messages
    IInbox public inbox;

    /// @inheritdoc ITokenPortal
    bytes32 public l2Bridge;

    /// @inheritdoc ITokenPortal
    bool public depositPaused;

    /// @inheritdoc ITokenPortal
    bool public withdrawPaused;

    /// @inheritdoc ITokenPortal
    ICapacityProvider public capacityProvider;

    /// @notice Per-account utilization tracking in underlying token amount
    mapping(address => uint256) private _accountUtilization;

    /// @notice Proxies trusted to attribute deposits and withdrawals to another address.
    EnumerableSet.AddressSet private _authorizedAttributionProxies;

    /// @notice Modifier to make a function callable only when the contract is not paused for deposits.
    modifier whenDepositNotPaused() {
        _requireDepositNotPaused();
        _;
    }

    /// @notice Modifier to make a function callable only when the contract is not paused for withdraw.
    modifier whenWithdrawNotPaused() {
        _requireWithdrawNotPaused();
        _;
    }

    /// @notice Construct the token portal
    /// @param registry - The Aztec registry this portal is bound to
    /// @param underlying_ - The underlying ERC20 token to be bridged
    /// @param permit2 - The Permit2 contract for permit-based token transfers
    /// @param owner - Portal owner with admin capabilities
    constructor(IRegistry registry, IERC20 underlying_, ISignatureTransfer permit2, address owner) Ownable(owner) {
        REGISTRY = registry;
        _UNDERLYING = underlying_;
        PERMIT2 = permit2;
    }

    /// @notice Initialize the portal with an Aztec rollup
    /// @param rollupVersion_ - Aztec rollup version
    /// @param l2Bridge_ - The L2 bridge this portal communicates with
    function initialize(uint256 rollupVersion_, bytes32 l2Bridge_) external onlyOwner {
        rollupVersion = rollupVersion_;
        rollup = IRollup(address(REGISTRY.getRollup(rollupVersion_)));
        assert(rollup.getVersion() == rollupVersion_);
        outbox = rollup.getOutbox();
        inbox = rollup.getInbox();
        l2Bridge = l2Bridge_;
    }

    /// @notice Admin function to set the capacity provider
    /// @param _capacityProvider - The capacity provider contract
    function setCapacityProvider(ICapacityProvider _capacityProvider) external onlyOwner {
        capacityProvider = _capacityProvider;
    }

    /// @notice Adds a proxy authorized to attribute deposits and withdrawals to another address.
    /// @param proxy - The proxy to authorize.
    /// @return True if successfully added, false if already authorized.
    function addAttributionProxy(address proxy) external onlyOwner returns (bool) {
        return _authorizedAttributionProxies.add(proxy);
    }

    /// @notice Removes a proxy's attribution authorization.
    /// @param proxy - The proxy to deauthorize.
    /// @return True if successfully removed, false if not authorized.
    function removeAttributionProxy(address proxy) external onlyOwner returns (bool) {
        return _authorizedAttributionProxies.remove(proxy);
    }

    /// @notice Admin function to pause deposit
    function pauseDeposit() external {
        _setDepositPaused(true);
    }

    /// @notice Admin function to unpause deposit
    function unpauseDeposit() external {
        _setDepositPaused(false);
    }

    /// @notice Admin function to pause withdraw
    function pauseWithdraw() external {
        _setWithdrawPaused(true);
    }

    /// @notice Admin function to unpause withdraw
    function unpauseWithdraw() external {
        _setWithdrawPaused(false);
    }

    /// @inheritdoc ITokenPortal
    function depositToAztecPrivate(uint128 amount, bytes32 claimSecretHash)
        external
        returns (bytes32 message, uint256 leafIndex)
    {
        return depositToAztecPrivate(amount, claimSecretHash, msg.sender);
    }

    /// @inheritdoc ITokenPortal
    function depositToAztecPrivate(uint128 amount, bytes32 claimSecretHash, TransferPermit calldata permit)
        external
        whenDepositNotPaused
        returns (bytes32 message, uint256 leafIndex)
    {
        _increaseUtilization(msg.sender, amount);

        // Transfer funds to portal through permit
        PERMIT2.permitTransferFrom(
            ISignatureTransfer.PermitTransferFrom({
                permitted: ISignatureTransfer.TokenPermissions({token: address(_UNDERLYING), amount: permit.amount}),
                nonce: permit.nonce,
                deadline: permit.deadline
            }),
            ISignatureTransfer.SignatureTransferDetails({to: address(this), requestedAmount: amount}),
            msg.sender,
            permit.signature
        );

        // Send message to L2
        (message, leafIndex) = _sendMintToPrivateMessage(amount, claimSecretHash);

        // Emit event for tracking purpose
        emit PrivateDepositToAztec(msg.sender, claimSecretHash, amount, message, leafIndex);
    }

    /// @inheritdoc ITokenPortal
    function withdraw(
        address recipient,
        uint128 amount,
        bool withCaller,
        address cancelCallerOnL1,
        bytes32 claimSecretHashForCancellation,
        uint64 validDurationSeconds,
        OutboxMessageMetadata calldata message
    ) external {
        withdraw(
            recipient,
            amount,
            withCaller,
            cancelCallerOnL1,
            claimSecretHashForCancellation,
            validDurationSeconds,
            message,
            recipient
        );
    }

    /// @inheritdoc ITokenPortal
    function cancelWithdraw(
        address recipient,
        uint128 amount,
        address callerOnL1,
        bool cancelWithCaller,
        bytes32 claimSecretHashForCancellation,
        uint64 validDurationSeconds,
        OutboxMessageMetadata calldata withdrawMessage
    ) external returns (bytes32 message, uint256 leafIndex) {
        bytes32 withdrawMessageId = withdrawMessage.computeMessageId();
        if (!withdrawMessage.isExpired(validDurationSeconds, rollup)) {
            revert OrderNotExpired(withdrawMessageId);
        }

        outbox.consume(
            DataStructures.L2ToL1Msg({
                sender: DataStructures.L2Actor(l2Bridge, rollupVersion),
                recipient: DataStructures.L1Actor(address(this), block.chainid),
                content: Hash.sha256ToField(
                    // solhint-disable-next-line gas-small-strings
                    abi.encodeWithSignature(
                        "withdraw(address,uint128,address,address,bytes32,uint64)",
                        recipient,
                        amount,
                        callerOnL1,
                        cancelWithCaller ? msg.sender : address(0),
                        claimSecretHashForCancellation,
                        validDurationSeconds
                    )
                )
            }),
            withdrawMessage
        );

        // Return funds to L2 to be claimed with claimSecretHashForCancellation
        (message, leafIndex) = _sendMintToPrivateMessage(amount, claimSecretHashForCancellation);

        emit WithdrawalCanceled(
            withdrawMessageId, recipient, claimSecretHashForCancellation, amount, message, leafIndex
        );
    }

    /// @inheritdoc ITokenPortal
    function underlying() external view returns (IERC20) {
        return _UNDERLYING;
    }

    /// @inheritdoc ITokenPortal
    function authorizedAttributionProxies() external view returns (address[] memory) {
        return _authorizedAttributionProxies.values();
    }

    /// @inheritdoc ITokenPortal
    function isAuthorizedAttributionProxy(address proxy) external view returns (bool) {
        return _authorizedAttributionProxies.contains(proxy);
    }

    /// @inheritdoc ITokenUtilizationMeter
    function token() external view returns (address) {
        return address(_UNDERLYING);
    }

    /// @inheritdoc ITokenUtilizationMeter
    function globalUtilization() external view returns (uint256) {
        return _UNDERLYING.balanceOf(address(this));
    }

    /// @inheritdoc ITokenUtilizationMeter
    function accountUtilization(address account) external view returns (uint256) {
        return _accountUtilization[account];
    }

    /// @inheritdoc ITokenPortal
    function depositToAztecPrivate(uint128 amount, bytes32 claimSecretHash, address depositor)
        public
        whenDepositNotPaused
        returns (bytes32 message, uint256 leafIndex)
    {
        // Paying for your own deposit needs no authorization, naming anyone else requires being
        // an allowed proxy.
        require(
            depositor == msg.sender || _authorizedAttributionProxies.contains(msg.sender), UnauthorizedAttribution()
        );

        _increaseUtilization(depositor, amount);

        // Transfer funds to portal
        _UNDERLYING.safeTransferFrom(msg.sender, address(this), amount);

        // Send message to L2
        (message, leafIndex) = _sendMintToPrivateMessage(amount, claimSecretHash);

        // Emit event for tracking purpose
        emit PrivateDepositToAztec(depositor, claimSecretHash, amount, message, leafIndex);
    }

    /// @inheritdoc ITokenPortal
    function withdraw(
        address recipient,
        uint128 amount,
        bool withCaller,
        address cancelCallerOnL1,
        bytes32 claimSecretHashForCancellation,
        uint64 validDurationSeconds,
        OutboxMessageMetadata calldata message,
        address withdrawer
    ) public whenWithdrawNotPaused {
        // Withdrawing for yourself no authorization, naming anyone else requires being
        // an allowed proxy.
        require(
            withdrawer == recipient || _authorizedAttributionProxies.contains(msg.sender), UnauthorizedAttribution()
        );
        if (message.isExpired(validDurationSeconds, rollup)) {
            revert OrderExpired(message.computeMessageId());
        }

        outbox.consume(
            DataStructures.L2ToL1Msg({
                sender: DataStructures.L2Actor(l2Bridge, rollupVersion),
                recipient: DataStructures.L1Actor(address(this), block.chainid),
                // Reconstruct the message hash sent from L2
                content: Hash.sha256ToField(
                    // solhint-disable-next-line gas-small-strings
                    abi.encodeWithSignature(
                        "withdraw(address,uint128,address,address,bytes32,uint64)",
                        recipient,
                        amount,
                        withCaller ? msg.sender : address(0),
                        cancelCallerOnL1,
                        claimSecretHashForCancellation,
                        validDurationSeconds
                    )
                )
            }),
            message
        );

        _decreaseUtilization(withdrawer, amount);

        // Release the funds after successful message consumption
        _UNDERLYING.safeTransfer(recipient, amount);

        // Emit event for tracking purpose
        emit Withdrawal(message.computeMessageId(), recipient, amount);
    }

    function _sendMintToPrivateMessage(uint128 amount, bytes32 claimSecretHash)
        internal
        returns (bytes32 message, uint256 leafIndex)
    {
        DataStructures.L2Actor memory actor = DataStructures.L2Actor(l2Bridge, rollupVersion);

        // Hash the message content to be reconstructed in the receiving contract
        bytes32 contentHash = Hash.sha256ToField(abi.encodeWithSignature("mint_to_private(uint128)", amount));

        return inbox.sendL2Message(actor, contentHash, claimSecretHash);
    }

    function _increaseUtilization(address account, uint256 amount) internal {
        if (address(capacityProvider) != address(0)) {
            require(capacityProvider.hasCapacityFor(account, address(_UNDERLYING), amount), CapacityExceeded());
        }
        _accountUtilization[account] += amount;
    }

    function _decreaseUtilization(address account, uint256 amount) internal {
        uint256 current = _accountUtilization[account];
        uint256 deduct = amount < current ? amount : current;
        _accountUtilization[account] = current - deduct;
    }

    function _setDepositPaused(bool paused) internal onlyOwner {
        depositPaused = paused;
    }

    function _setWithdrawPaused(bool paused) internal onlyOwner {
        withdrawPaused = paused;
    }

    function _requireDepositNotPaused() internal view {
        require(!depositPaused, DepositPaused());
    }

    function _requireWithdrawNotPaused() internal view {
        require(!withdrawPaused, WithdrawPaused());
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@aztec-blob-lib/=lib/aztec-packages/l1-contracts/src/core/libraries/rollup/",
    "@test/=lib/aztec-packages/l1-contracts/test/",
    "@openzeppelin/=lib/aztec-packages/l1-contracts/lib/openzeppelin-contracts/",
    "@oz/=lib/aztec-packages/l1-contracts/lib/openzeppelin-contracts/contracts/",
    "@aztec/=lib/aztec-packages/l1-contracts/src/",
    "@aztectest/=lib/aztec-packages/l1-contracts/test/",
    "@permit2/=lib/permit2/src/",
    "forge-std/=lib/aztec-packages/l1-contracts/lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.