Перейти к содержимому
Проверенный контрактТочноеMIT

BridgeVault

Адрес0x4044087dbda5846bf8a7970dc515a33eb319f3c2
Баланс

0 ETH

 

Транзакций

4

 

Компилятор

solc 0.8.30

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.30+commit.73712a01
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 436 240
Транзакция создания
0xe07c45b9e9…7cc693d5e0

contracts/BridgeVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {ExactToken} from "./ExactToken.sol";
import {IAOUSDSDistribution} from "./IAOUSDSDistribution.sol";
import {USDSCohort} from "./USDSCohort.sol";

/// @title BridgeVault
/// @notice Capped USDS principal custody for one EVM-to-AO receipt route.
/// @dev Each deposit stakes through a fresh, permanently closed cohort. The
///      controller attests AO mint confirmation and escrow/burn authorization;
///      this contract does not verify native AO proofs. All AO staking rewards
///      belong to the manager, with no reward entitlement for receipt holders.
contract BridgeVault {
    error InvalidConfiguration();
    error UpstreamConfigurationChanged();
    error UnauthorizedController();
    error InvalidRecipient();
    error InvalidAmount();
    error InvalidCallValue();
    error ExposureCapExceeded();
    error DepositLimitExceeded();
    error UnknownDeposit();
    error DepositNotActivated();
    error DepositAlreadyActivated();
    error InvalidMintTransaction();
    error MintTransactionAlreadyUsed();
    error InvalidRedemptionId();
    error RedemptionAlreadyUsed();
    error InvalidReceiptCommitment();
    error ReceiptCommitmentAlreadyUsed();
    error InsufficientUnqueuedPrincipal();
    error InsufficientActivatedPrincipal();
    error InsufficientQueuedDemand();
    error UnknownRedemption();
    error RedemptionAlreadyPaid();
    error InsufficientLiquidPrincipal();
    error ReentrantCall();
    error DirectNativeTransferDisabled();

    struct Config {
        bytes32 routeId;
        bytes32 destinationProcess;
        address controller;
        address asset;
        address upstream;
        address savingsVault;
        uint256 maxExposure;
        uint256 maxDeposit;
        bytes32 managerRewardRecipient;
    }

    struct DepositInfo {
        address cohort;
        uint256 creditedPrincipal;
        bytes32 aoMintTxId;
    }

    struct Redemption {
        address recipient;
        uint256 amount;
        bytes32 receiptCommitment;
        bool paid;
    }

    // ABI/order/indexing are part of the source-observer protocol.
    event Deposited(
        bytes32 indexed depositId,
        bytes32 indexed routeId,
        bytes32 indexed aoRecipient,
        bytes32 destinationProcess,
        address asset,
        uint256 amount,
        address depositor
    );
    event StakeCommitted(
        bytes32 indexed depositId,
        address indexed cohort,
        address indexed upstream,
        uint256 creditedPrincipal,
        bytes32 rewardRecipient,
        uint256 unlockAfter
    );
    event DepositActivated(bytes32 indexed depositId, bytes32 indexed aoMintTxId, uint256 principal);
    event RedemptionRequested(
        bytes32 indexed redemptionId, bytes32 indexed routeId, address indexed recipient,
        address asset, uint256 amount, bytes32 receiptCommitment
    );
    event CohortFunded(bytes32 indexed depositId, address indexed cohort, uint256 amount);
    event CohortReconciled(bytes32 indexed depositId, address indexed cohort, uint256 amount);
    event RedemptionPaid(
        bytes32 indexed redemptionId, bytes32 indexed routeId, address indexed recipient,
        address asset, uint256 amount, bytes32 receiptCommitment
    );

    bytes32 public immutable routeId;
    bytes32 public immutable destinationProcess;
    address public immutable controller;
    address public immutable asset;
    address public immutable upstream;
    address public immutable savingsVault;
    uint256 public immutable maxExposure;
    uint256 public immutable maxDeposit;
    bytes32 public immutable managerRewardRecipient;

    uint256 public depositNonce;
    /// @notice Pending mints + live receipts + queued exits, less actual payouts.
    uint256 public outstandingPrincipal;
    /// @notice Mint-confirmed principal, including queued exits, less payouts.
    uint256 public activatedPrincipal;
    uint256 public pendingExitPrincipal;
    /// @notice Attributed funds returned from activated cohorts, less payouts.
    uint256 public liquidPrincipal;

    mapping(bytes32 depositId => DepositInfo) public deposits;
    mapping(bytes32 depositId => bytes32) public depositCommitments;
    mapping(bytes32 aoMintTxId => bool) public usedMintTransactions;
    mapping(bytes32 redemptionId => Redemption) public redemptions;
    mapping(bytes32 receiptCommitment => bool) public usedReceiptCommitments;
    uint256 private entered;

    constructor(Config memory config) {
        if (config.routeId == bytes32(0) || config.destinationProcess == bytes32(0)
            || config.controller == address(0) || config.managerRewardRecipient == bytes32(0)
            || config.asset.code.length == 0 || config.upstream.code.length == 0
            || config.savingsVault.code.length == 0 || config.maxExposure == 0
            || config.maxDeposit == 0 || config.maxDeposit > config.maxExposure
            || config.asset == config.upstream || config.asset == config.savingsVault) {
            revert InvalidConfiguration();
        }
        routeId = config.routeId;
        destinationProcess = config.destinationProcess;
        controller = config.controller;
        asset = config.asset;
        upstream = config.upstream;
        savingsVault = config.savingsVault;
        maxExposure = config.maxExposure;
        maxDeposit = config.maxDeposit;
        managerRewardRecipient = config.managerRewardRecipient;
        _checkConfiguration();
    }

    modifier nonReentrant() {
        if (entered != 0) revert ReentrantCall();
        entered = 1;
        _;
        entered = 0;
    }

    modifier onlyController() {
        if (msg.sender != controller) revert UnauthorizedController();
        _;
    }

    /// @notice Atomically accepts USDS, stakes, and commits actual principal.
    /// @dev No receipt event is emitted for mere funding or an approval.
    function deposit(uint256 amount, bytes32 aoRecipient)
        external payable nonReentrant returns (bytes32 depositId)
    {
        if (msg.value != 0) revert InvalidCallValue();
        if (aoRecipient == bytes32(0)) revert InvalidRecipient();
        if (amount == 0) revert InvalidAmount();
        if (amount > maxDeposit) revert DepositLimitExceeded();
        if (amount > maxExposure - outstandingPrincipal) revert ExposureCapExceeded();
        _checkConfiguration();
        ExactToken.transferFrom(asset, msg.sender, address(this), amount);
        USDSCohort cohort = new USDSCohort(asset, upstream, savingsVault, managerRewardRecipient);
        ExactToken.transfer(asset, address(cohort), amount);
        (uint256 credited, uint256 unlock) = cohort.stake(amount);
        depositId = keccak256(abi.encode(block.chainid, address(this), ++depositNonce));
        outstandingPrincipal += credited;
        deposits[depositId] = DepositInfo(address(cohort), credited, bytes32(0));
        depositCommitments[depositId] = keccak256(
            abi.encode(routeId, aoRecipient, destinationProcess, asset, credited, msg.sender)
        );
        // Keep these adjacent: the observer requires the companion at logIndex-1.
        emit StakeCommitted(depositId, address(cohort), upstream, credited, managerRewardRecipient, unlock);
        emit Deposited(depositId, routeId, aoRecipient, destinationProcess, asset, credited, msg.sender);
    }

    /// @notice Acknowledge a confirmed AO mint exactly once.
    /// @dev An unknown/timed-out AO mint remains pending indefinitely. There is
    ///      no refund, reanchor, cancellation, or timeout-based activation path.
    function activateDeposit(bytes32 depositId, bytes32 aoMintTxId) external nonReentrant onlyController {
        DepositInfo storage info = deposits[depositId];
        if (info.cohort == address(0)) revert UnknownDeposit();
        if (info.aoMintTxId != bytes32(0)) revert DepositAlreadyActivated();
        if (aoMintTxId == bytes32(0)) revert InvalidMintTransaction();
        if (usedMintTransactions[aoMintTxId]) revert MintTransactionAlreadyUsed();
        info.aoMintTxId = aoMintTxId;
        usedMintTransactions[aoMintTxId] = true;
        activatedPrincipal += info.creditedPrincipal;
        emit DepositActivated(depositId, aoMintTxId, info.creditedPrincipal);
    }

    /// @notice Queue immutable payout terms from a trusted AO escrow/burn attestation.
    /// @dev Commitment is opaque here: authenticity and AO replay scope are the
    ///      controller's responsibility. Neither queueing nor funding frees cap.
    function requestRedemption(bytes32 redemptionId, address recipient, uint256 amount, bytes32 receiptCommitment)
        external nonReentrant onlyController
    {
        if (redemptionId == bytes32(0)) revert InvalidRedemptionId();
        if (redemptions[redemptionId].recipient != address(0)) revert RedemptionAlreadyUsed();
        if (recipient == address(0) || recipient == address(this)) revert InvalidRecipient();
        if (amount == 0) revert InvalidAmount();
        if (receiptCommitment == bytes32(0)) revert InvalidReceiptCommitment();
        if (usedReceiptCommitments[receiptCommitment]) revert ReceiptCommitmentAlreadyUsed();
        if (amount > outstandingPrincipal - pendingExitPrincipal) revert InsufficientUnqueuedPrincipal();
        if (amount > activatedPrincipal - pendingExitPrincipal) revert InsufficientActivatedPrincipal();
        redemptions[redemptionId] = Redemption(recipient, amount, receiptCommitment, false);
        usedReceiptCommitments[receiptCommitment] = true;
        pendingExitPrincipal += amount;
        emit RedemptionRequested(redemptionId, routeId, recipient, asset, amount, receiptCommitment);
    }

    /// @notice Fund unpaid queued exits from a mature cohort.
    /// @dev The request is limited to unfunded demand. If it leaves upstream
    ///      principal below the minimum, that bounded dust is withdrawn too and
    ///      remains attributed liquid principal. No cohort can be relocked.
    function fundCohort(bytes32 depositId, uint256 amount) external nonReentrant {
        DepositInfo storage info = _activeDeposit(depositId);
        if (amount == 0) revert InvalidAmount();
        if (liquidPrincipal >= pendingExitPrincipal || amount > pendingExitPrincipal - liquidPrincipal) {
            revert InsufficientQueuedDemand();
        }
        uint256 funded = USDSCohort(info.cohort).withdraw(amount);
        liquidPrincipal += funded;
        emit CohortFunded(depositId, info.cohort, funded);
    }

    /// @notice Recover matched forced-ejection proceeds after mint confirmation.
    /// @dev May precede maturity/queueing because these funds are already unstaked.
    function reconcileCohort(bytes32 depositId) external nonReentrant returns (uint256 amount) {
        DepositInfo storage info = _activeDeposit(depositId);
        amount = USDSCohort(info.cohort).reconcile();
        liquidPrincipal += amount;
        emit CohortReconciled(depositId, info.cohort, amount);
    }

    /// @notice Anyone may complete a funded queue item exactly once.
    function payRedemption(bytes32 redemptionId) external nonReentrant {
        Redemption storage redemption = redemptions[redemptionId];
        if (redemption.recipient == address(0)) revert UnknownRedemption();
        if (redemption.paid) revert RedemptionAlreadyPaid();
        uint256 amount = redemption.amount;
        if (amount > liquidPrincipal) revert InsufficientLiquidPrincipal();
        redemption.paid = true;
        pendingExitPrincipal -= amount;
        liquidPrincipal -= amount;
        activatedPrincipal -= amount;
        outstandingPrincipal -= amount;
        ExactToken.transfer(asset, redemption.recipient, amount);
        emit RedemptionPaid(
            redemptionId, routeId, redemption.recipient, asset, amount, redemption.receiptCommitment
        );
    }

    function pendingMintPrincipal() external view returns (uint256) {
        return outstandingPrincipal - activatedPrincipal;
    }

    function _activeDeposit(bytes32 depositId) private view returns (DepositInfo storage info) {
        info = deposits[depositId];
        if (info.cohort == address(0)) revert UnknownDeposit();
        if (info.aoMintTxId == bytes32(0)) revert DepositNotActivated();
    }

    function _checkConfiguration() private view {
        IAOUSDSDistribution distribution = IAOUSDSDistribution(upstream);
        if (distribution.depositToken() != asset || distribution.vaultAddress() != savingsVault
            || distribution.vault() != savingsVault) revert UpstreamConfigurationChanged();
    }

    receive() external payable { revert DirectNativeTransferDisabled(); }
}

contracts/ExactToken.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/// @dev Exact-transfer ERC20 helpers. USDS is the supported production asset.
library ExactToken {
    error AssetHasNoCode();
    error TokenBalanceQueryFailed();
    error TokenCallFailed();
    error UnsupportedTokenTransfer();

    function balance(address token, address account) internal view returns (uint256) {
        if (token.code.length == 0) revert AssetHasNoCode();
        (bool ok, bytes memory result) = token.staticcall(abi.encodeWithSelector(bytes4(0x70a08231), account));
        if (!ok || result.length != 32) revert TokenBalanceQueryFailed();
        return abi.decode(result, (uint256));
    }

    function callToken(address token, bytes memory data) internal {
        if (token.code.length == 0) revert AssetHasNoCode();
        (bool ok, bytes memory result) = token.call(data);
        if (!ok) revert TokenCallFailed();
        if (result.length == 0) return;
        if (result.length != 32) revert TokenCallFailed();
        uint256 returned;
        assembly ("memory-safe") { returned := mload(add(result, 0x20)) }
        if (returned != 1) revert TokenCallFailed();
    }

    function approve(address token, address spender, uint256 amount) internal {
        callToken(token, abi.encodeWithSelector(bytes4(0x095ea7b3), spender, amount));
    }

    function transfer(address token, address recipient, uint256 amount) internal {
        uint256 beforeSender = balance(token, address(this));
        uint256 beforeRecipient = balance(token, recipient);
        callToken(token, abi.encodeWithSelector(bytes4(0xa9059cbb), recipient, amount));
        _check(token, address(this), recipient, amount, beforeSender, beforeRecipient);
    }

    function transferFrom(address token, address sender, address recipient, uint256 amount) internal {
        uint256 beforeSender = balance(token, sender);
        uint256 beforeRecipient = balance(token, recipient);
        callToken(token, abi.encodeWithSelector(bytes4(0x23b872dd), sender, recipient, amount));
        _check(token, sender, recipient, amount, beforeSender, beforeRecipient);
    }

    function _check(
        address token, address sender, address recipient, uint256 amount,
        uint256 beforeSender, uint256 beforeRecipient
    ) private view {
        uint256 afterSender = balance(token, sender);
        uint256 afterRecipient = balance(token, recipient);
        if (afterSender > beforeSender || afterRecipient < beforeRecipient) revert UnsupportedTokenTransfer();
        if (beforeSender - afterSender != amount || afterRecipient - beforeRecipient != amount) {
            revert UnsupportedTokenTransfer();
        }
    }
}

contracts/IAOUSDSDistribution.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/// @dev ABI of the official USDS Distribution, not the pool-indexed DAI/stETH ABI.
interface IAOUSDSDistribution {
    struct UserData {
        uint128 lastStake;
        uint256 deposited;
    }

    function depositToken() external view returns (address);
    function vaultAddress() external view returns (address);
    function vault() external view returns (address);
    function minimalStake() external view returns (uint256);
    function withdrawLockPeriodAfterStake() external view returns (uint128);
    function usersData(address user) external view returns (UserData memory);
    function stake(uint256 amount, bytes32 arweaveAddress) external;
    function withdraw(uint256 amount, bytes32 arweaveAddress) external;
}

contracts/USDSCohort.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {ExactToken} from "./ExactToken.sol";
import {IAOUSDSDistribution} from "./IAOUSDSDistribution.sol";

/// @notice A closed, single-stake upstream account owned by one BridgeVault.
/// @dev No top-up, arbitrary call, reward redirection, or administrative sweep.
contract USDSCohort {
    error OnlyVault();
    error AlreadyStaked();
    error InvalidPrincipal();
    error UpstreamConfigurationChanged();
    error UpstreamPositionChanged();
    error UnsupportedStakeCredit();
    error PrincipalLocked();
    error InvalidWithdrawalAmount();
    error WithdrawalMismatch();
    error MissingEjectionBacking();
    error NothingToReconcile();

    address public immutable vault;
    address public immutable asset;
    address public immutable upstream;
    address public immutable savingsVault;
    bytes32 public immutable managerRewardRecipient;

    bool public staked;
    uint128 public stakeTimestamp;
    uint256 public unlockAfter;
    uint256 public principal;
    /// @notice Original principal less amounts transferred to the parent.
    ///         Includes upstream stake and matched, unswept ejection proceeds.
    uint256 public remainingPrincipal;

    constructor(address asset_, address upstream_, address savingsVault_, bytes32 rewardRecipient_) {
        vault = msg.sender;
        asset = asset_;
        upstream = upstream_;
        savingsVault = savingsVault_;
        managerRewardRecipient = rewardRecipient_;
    }

    modifier onlyVault() {
        if (msg.sender != vault) revert OnlyVault();
        _;
    }

    function stake(uint256 amount) external onlyVault returns (uint256 credited, uint256 unlock) {
        if (staked) revert AlreadyStaked();
        if (amount == 0) revert InvalidPrincipal();
        _checkConfiguration();
        IAOUSDSDistribution distribution = IAOUSDSDistribution(upstream);
        IAOUSDSDistribution.UserData memory beforePosition = distribution.usersData(address(this));
        if (beforePosition.deposited != 0 || beforePosition.lastStake != 0) revert UpstreamPositionChanged();
        uint256 beforeBalance = ExactToken.balance(asset, address(this));
        if (beforeBalance < amount) revert InvalidPrincipal();
        staked = true;
        ExactToken.approve(asset, upstream, amount);
        distribution.stake(amount, managerRewardRecipient);
        ExactToken.approve(asset, upstream, 0);

        IAOUSDSDistribution.UserData memory afterPosition = distribution.usersData(address(this));
        uint256 afterBalance = ExactToken.balance(asset, address(this));
        credited = afterPosition.deposited - beforePosition.deposited;
        // The official implementation keeps short-credit dust upstream. Revert
        // rather than issue an unbacked receipt or subsidize a refund.
        if (credited != amount || afterBalance > beforeBalance || beforeBalance - afterBalance != amount) {
            revert UnsupportedStakeCredit();
        }
        if (afterPosition.lastStake != block.timestamp) revert UpstreamPositionChanged();
        stakeTimestamp = afterPosition.lastStake;
        unlock = uint256(stakeTimestamp) + uint256(distribution.withdrawLockPeriodAfterStake());
        unlockAfter = unlock;
        principal = credited;
        remainingPrincipal = credited;
    }

    /// @notice Per-cohort attribution; surplus donations never enlarge backing.
    /// @return stakedPrincipal Current recorded upstream principal.
    /// @return matchedLoosePrincipal Book principal returned by ejection.
    /// @return looseUSDS Raw balance, including any unmatched donations.
    function backing() external view returns (
        uint256 stakedPrincipal, uint256 matchedLoosePrincipal, uint256 looseUSDS
    ) {
        (IAOUSDSDistribution.UserData memory position, uint256 loose, uint256 balance_) = _position();
        return (position.deposited, loose, balance_);
    }

    /// @dev Parent limits the requested amount to unfunded queued demand. A
    ///      remainder below the upstream minimum is also withdrawn, leaving a
    ///      bounded surplus in the parent's attributed principal reserve.
    /// @return funded Actual principal returned, including any minimum dust.
    function withdraw(uint256 amount) external onlyVault returns (uint256 funded) {
        _checkConfiguration();
        (IAOUSDSDistribution.UserData memory beforePosition,, uint256 beforeBalance) = _position();
        if (block.timestamp <= unlockAfter) revert PrincipalLocked();
        if (amount == 0 || amount > beforePosition.deposited) revert InvalidWithdrawalAmount();
        uint256 remainder = beforePosition.deposited - amount;
        if (remainder != 0 && remainder < IAOUSDSDistribution(upstream).minimalStake()) {
            amount = beforePosition.deposited;
            remainder = 0;
        }
        IAOUSDSDistribution(upstream).withdraw(amount, managerRewardRecipient);
        IAOUSDSDistribution.UserData memory afterPosition = IAOUSDSDistribution(upstream).usersData(address(this));
        uint256 afterBalance = ExactToken.balance(asset, address(this));
        if (afterPosition.lastStake != stakeTimestamp || afterPosition.deposited != remainder) {
            revert WithdrawalMismatch();
        }
        if (afterBalance < beforeBalance || afterBalance - beforeBalance != amount) revert WithdrawalMismatch();
        remainingPrincipal -= amount;
        ExactToken.transfer(asset, vault, amount);
        return amount;
    }

    /// @dev Only principal reduction matched by loose USDS is recoverable.
    ///      Ejection bypasses the normal maturity lock upstream.
    function reconcile() external onlyVault returns (uint256 amount) {
        _checkConfiguration();
        (, amount,) = _position();
        if (amount == 0) revert NothingToReconcile();
        remainingPrincipal -= amount;
        ExactToken.transfer(asset, vault, amount);
    }

    function _position() private view returns (
        IAOUSDSDistribution.UserData memory position, uint256 matchedLoose, uint256 looseBalance
    ) {
        position = IAOUSDSDistribution(upstream).usersData(address(this));
        if (!staked || position.lastStake != stakeTimestamp || position.deposited > remainingPrincipal) {
            revert UpstreamPositionChanged();
        }
        matchedLoose = remainingPrincipal - position.deposited;
        looseBalance = ExactToken.balance(asset, address(this));
        if (looseBalance < matchedLoose) revert MissingEjectionBacking();
    }

    function _checkConfiguration() private view {
        IAOUSDSDistribution distribution = IAOUSDSDistribution(upstream);
        if (distribution.depositToken() != asset || distribution.vaultAddress() != savingsVault
            || distribution.vault() != savingsVault) revert UpstreamConfigurationChanged();
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.