AVAX Price: $51.65 (-2.19%)
 

Overview

AVAX Balance

Avalanche C-Chain LogoAvalanche C-Chain LogoAvalanche C-Chain Logo0 AVAX

AVAX Value

$0.00
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xec92BCD9...584905F2F
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
Vault

Compiler Version
v0.8.23+commit.f704f362

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 18 : Vault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;

import {IPhutureOnDonationCallback} from "./interfaces/IPhutureOnDonationCallback.sol";
import {IPhutureOnConsumeCallback} from "./interfaces/IPhutureOnConsumeCallback.sol";
import {IVault} from "./interfaces/IVault.sol";

import {BitSet} from "./libraries/BitSet.sol";
import {CurrencyLib, Currency} from "./libraries/CurrencyLib.sol";
import {AnatomyValidationLib} from "./libraries/AnatomyValidationLib.sol";
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";
import {SafeCastLib} from "solmate/utils/SafeCastLib.sol";
import {a160u96} from "./utils/a160u96.sol";
import {CurrencyRegistryLib} from "./libraries/CurrencyRegistryLib.sol";

import {Extsload} from "./Extsload.sol";
import {Owned} from "solmate/auth/Owned.sol";
import {ReentrancyGuard} from "solmate/utils/ReentrancyGuard.sol";

contract Vault is IVault, Owned, ReentrancyGuard, Extsload {
    using BitSet for uint256[];
    using CurrencyLib for *;
    using FixedPointMathLib for uint256;
    using SafeCastLib for uint256;
    using CurrencyRegistryLib for CurrencyRegistryLib.Registry;

    uint8 internal constant VAULT_REBALANCING_FLAG = 0x01;

    uint8 internal rebalancingFlags;

    address internal orderBook;
    address internal messenger;
    uint256 internal anatomySnapshot;

    CurrencyRegistryLib.Registry internal registry;

    // packed currency balances for snapshot
    mapping(uint256 => a160u96[]) internal currenciesOf;

    mapping(uint256 => bytes32) internal currencyHashOf;
    // bit set, stores if currency balance exists for snapshot
    mapping(uint256 => uint256[]) internal currencySetOf;

    mapping(Currency => uint96) internal unaccountedBalanceOf;

    // k balance for snapshot
    mapping(uint256 => mapping(address => uint256)) public kBalanceWads;

    event SnapshotTransfer(uint256 snapshot, uint256 amount, address indexed from, address indexed to);
    event StartRebalancing(uint256 snapshot, uint256 kBalance, CurrencyWithdrawal withdrawals);
    event FinishRebalancing(uint256 snapshot, a160u96[] currencies);
    event Donate(Currency currency, uint256 amount);
    event Consume(Currency currency, uint256 amount);

    error Forbidden();
    error HashMismatch();
    error Rebalancing();
    error InvalidWithdrawal();

    modifier only(address addr) {
        _checkSender(addr);
        _;
    }

    constructor(address _owner, address _messenger) Owned(_owner) {
        messenger = _messenger;
        currencyHashOf[0] = keccak256(abi.encode(new a160u96[](0)));
    }

    receive() external payable {}

    function setMessenger(address _messenger) external only(owner) {
        messenger = _messenger;
    }

    function setOrderBook(address _orderBook) external only(owner) {
        orderBook = _orderBook;
    }

    function startRebalancingPhase(CurrencyWithdrawal calldata withdrawals) external only(messenger) {
        _startRebalancingPhase(withdrawals);
    }

    function finishRebalancingPhase(EndRebalancingParams calldata params)
        external
        only(messenger)
        returns (bytes32 resultHash)
    {
        uint8 _rebalancingFlags = rebalancingFlags;
        if (_rebalancingFlags == 0) revert Rebalancing();

        uint256 snapshot = anatomySnapshot;

        // check if anatomy and withdrawal hashes match the stored version
        // hash allows us to recover anatomy and withdrawals from memory
        if (currencyHashOf[snapshot] != keccak256(abi.encode(params.withdrawals, params.lastKBalance))) {
            revert HashMismatch();
        }

        uint256 lastSnapshot;
        unchecked {
            // cannot overflow, snapshot > 0
            lastSnapshot = snapshot - 1;
        }

        if (currencyHashOf[lastSnapshot] != keccak256(abi.encode(params.anatomyCurrencies))) {
            revert HashMismatch();
        }

        AnatomyValidationLib.validate(
            unaccountedBalanceOf, currencySetOf[lastSnapshot], registry.currenciesHash, params
        );

        currenciesOf[snapshot] = params.newAnatomy.currencies;
        currencyHashOf[snapshot] = keccak256(abi.encode(params.newAnatomy.currencies));
        currencySetOf[snapshot] = params.newAnatomy.currencyIndexSet;

        // issue the new sub index k shares
        kBalanceWads[snapshot][address(this)] = FixedPointMathLib.WAD;
        emit SnapshotTransfer(snapshot, FixedPointMathLib.WAD, address(0), address(this));

        // end vault rebalancing phase
        rebalancingFlags = _rebalancingFlags & ~VAULT_REBALANCING_FLAG;

        emit FinishRebalancing(snapshot, params.newAnatomy.currencies);

        resultHash = keccak256(
            abi.encode(
                RebalancingResult(
                    block.chainid, snapshot, params.newAnatomy.currencyIndexSet, params.newAnatomy.currencies
                )
            )
        );
    }

    function donate(Currency currency, bytes memory data) external nonReentrant only(orderBook) {
        uint256 balanceBefore = currency.balanceOfSelf();

        IPhutureOnDonationCallback(msg.sender).phutureOnDonationCallbackV1(data);

        uint96 delta = (currency.balanceOfSelf() - balanceBefore).safeCastTo96();
        unaccountedBalanceOf[currency] += delta;
        emit Donate(currency, delta);
    }

    function consume(Currency currency, uint96 amount, address target, bytes calldata data) external only(orderBook) {
        if (rebalancingFlags == 0) revert Rebalancing();

        unaccountedBalanceOf[currency] -= amount;

        currency.transfer(target, amount);
        IPhutureOnConsumeCallback(target).phutureOnConsumeCallbackV1(data);

        emit Consume(currency, amount);
    }

    function registerCurrencies(Currency[] calldata currencies)
        external
        only(owner)
        returns (RegisterCurrenciesResult memory result)
    {
        result.currencies = currencies;
        for (uint256 i; i < currencies.length; ++i) {
            result.currenciesHash = registry.registerCurrency(currencies[i]);
        }
    }

    function transferLatestSnapshot(address recipient, uint256 kAmountWads)
        external
        only(messenger)
        returns (uint256 snapshot)
    {
        if (rebalancingFlags != 0) revert Rebalancing();

        snapshot = anatomySnapshot;
        _transferSnapshot(snapshot, kAmountWads, address(this), recipient);
    }

    function withdraw(uint256 snapshot, uint256 kAmount, address recipient) external {
        _burnSnapshot(snapshot, msg.sender, kAmount);

        a160u96[] memory currencies = currenciesOf[snapshot];
        uint256 length = currencies.length;

        for (uint256 i; i < length; ++i) {
            (Currency currency, uint96 value) = currencies[i].unpack();
            uint256 assets = kAmount.mulWadDown(value);

            if (assets != 0) currency.transfer(recipient, assets);
        }
    }

    function _startRebalancingPhase(CurrencyWithdrawal calldata withdrawals) internal virtual {
        if (rebalancingFlags & VAULT_REBALANCING_FLAG != 0) revert Rebalancing();

        uint256 snapshot = anatomySnapshot;

        Currency[] memory currencies = registry.currencies;
        uint256[] memory currencySet = currencySetOf[snapshot];
        uint256 withdrawalIndex;
        for (uint256 i; i < currencies.length; ++i) {
            if (withdrawals.currencyIndexSet.contains(i)) {
                if (!currencySet.contains(i)) revert InvalidWithdrawal();

                unaccountedBalanceOf[currencies[i]] += withdrawals.amounts[withdrawalIndex];

                unchecked {
                    ++withdrawalIndex;
                }
            }
        }

        // enter rebalancing phase
        uint256 kBalance = kBalanceWads[snapshot][address(this)];

        _burnSnapshot(snapshot, address(this), kBalance);

        currencyHashOf[++snapshot] = keccak256(abi.encode(withdrawals, kBalance));
        rebalancingFlags |= VAULT_REBALANCING_FLAG;
        anatomySnapshot = snapshot;

        emit StartRebalancing(snapshot, kBalance, withdrawals);
    }

    function _burnSnapshot(uint256 snapshot, address from, uint256 kAmountWads) internal {
        if (kAmountWads == 0) return;

        kBalanceWads[snapshot][from] -= kAmountWads;
        emit SnapshotTransfer(snapshot, kAmountWads, from, address(0));
    }

    function _transferSnapshot(uint256 snapshot, uint256 kAmountWads, address from, address recipient) internal {
        kBalanceWads[snapshot][from] -= kAmountWads;
        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            kBalanceWads[snapshot][recipient] += kAmountWads;
        }
        emit SnapshotTransfer(snapshot, kAmountWads, from, recipient);
    }

    function _checkSender(address addr) private view {
        if (msg.sender != addr) revert Forbidden();
    }
}

File 2 of 18 : IPhutureOnDonationCallback.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.23;

interface IPhutureOnDonationCallback {
    function phutureOnDonationCallbackV1(bytes calldata data) external;
}

File 3 of 18 : IPhutureOnConsumeCallback.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.23;

interface IPhutureOnConsumeCallback {
    function phutureOnConsumeCallbackV1(bytes calldata data) external;
}

File 4 of 18 : IVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.23;

import {Currency} from "../libraries/CurrencyLib.sol";
import {a160u96} from "../utils/a160u96.sol";

interface IVault {
    struct CurrencyWithdrawal {
        uint256[] currencyIndexSet;
        uint96[] amounts;
    }

    struct SnapshotAnatomy {
        a160u96[] currencies;
        uint256[] currencyIndexSet;
    }

    struct EndRebalancingParams {
        a160u96[] anatomyCurrencies;
        SnapshotAnatomy newAnatomy;
        CurrencyWithdrawal withdrawals;
        uint256 lastKBalance;
        Currency[] currencies;
    }

    struct RebalancingResult {
        uint256 chainId;
        uint256 snapshot;
        uint256[] currencyIdSet;
        a160u96[] currencies;
    }

    struct RegisterCurrenciesResult {
        Currency[] currencies;
        bytes32 currenciesHash;
    }

    function setOrderBook(address _orderBook) external;
    function setMessenger(address _messenger) external;

    function startRebalancingPhase(CurrencyWithdrawal calldata withdrawals) external;

    function finishRebalancingPhase(EndRebalancingParams calldata params) external returns (bytes32);
    function transferLatestSnapshot(address recipient, uint256 kAmountWads) external returns (uint256);
    function withdraw(uint256 snapshot, uint256 kAmount, address recipient) external;
    function registerCurrencies(Currency[] calldata currencies) external returns (RegisterCurrenciesResult memory);

    function donate(Currency currency, bytes memory data) external;
    function consume(Currency currency, uint96 amount, address target, bytes calldata data) external;
}

File 5 of 18 : BitSet.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;

/// @title BitSet
/// @notice A library for managing bitsets
library BitSet {
    uint256 private constant WORD_SHIFT = 8;

    /// @notice Checks if the next bit is set in the given word starting from the given bit position
    ///
    /// @param word The word to check
    /// @param bit The bit position
    ///
    /// @return r True if the next bit is set, false otherwise
    function hasNext(uint256 word, uint256 bit) internal pure returns (bool r) {
        assembly ("memory-safe") {
            r := and(shr(bit, word), 1)
        }
    }

    /// @notice Finds the position of the next set bit in the given word starting from the given bit position
    ///
    /// @dev This function uses a lookup table approach to find the position of the next set bit.
    ///      It first shifts the word right by the given bit position and then checks the lower 3 bits
    ///      of the resulting word to determine the position of the next set bit.
    ///      If no set bit is found, it returns 256 to indicate that there are no more set bits.
    ///
    /// @param word The word to search
    /// @param b The starting bit position
    ///
    /// @return nb The position of the next set bit
    function find(uint256 word, uint256 b) internal pure returns (uint256 nb) {
        assembly ("memory-safe") {
            let w := shr(b, word)
            switch w
            case 0 {
                // no more bits
                nb := 256
            }
            default {
                // 0b000 = 0
                // 0b001 = 1
                // 0b010 = 2
                // 0b011 = 3
                // 0b100 = 4
                // 0b101 = 5
                // 0b110 = 6
                // 0b111 = 7
                switch and(w, 7)
                case 0 { nb := add(lsb(w), b) }
                case 2 { nb := add(b, 1) }
                case 4 { nb := add(b, 2) }
                case 6 { nb := add(b, 1) }
                default { nb := b }
            }

            function lsb(x) -> r {
                if iszero(x) { revert(0, 0) }
                r := 255
                switch gt(and(x, 0xffffffffffffffffffffffffffffffff), 0)
                case 1 { r := sub(r, 128) }
                case 0 { x := shr(128, x) }

                switch gt(and(x, 0xffffffffffffffff), 0)
                case 1 { r := sub(r, 64) }
                case 0 { x := shr(64, x) }

                switch gt(and(x, 0xffffffff), 0)
                case 1 { r := sub(r, 32) }
                case 0 { x := shr(32, x) }

                switch gt(and(x, 0xffff), 0)
                case 1 { r := sub(r, 16) }
                case 0 { x := shr(16, x) }

                switch gt(and(x, 0xff), 0)
                case 1 { r := sub(r, 8) }
                case 0 { x := shr(8, x) }

                switch gt(and(x, 0xf), 0)
                case 1 { r := sub(r, 4) }
                case 0 { x := shr(4, x) }

                switch gt(and(x, 0x3), 0)
                case 1 { r := sub(r, 2) }
                case 0 { x := shr(2, x) }

                switch gt(and(x, 0x1), 0)
                case 1 { r := sub(r, 1) }
            }
        }
    }

    /// @notice Computes the value at the given word index and bit position
    ///
    /// @param wordIndex The index of the word
    /// @param bit The bit position within the word
    ///
    /// @return r The computed value
    function valueAt(uint256 wordIndex, uint256 bit) internal pure returns (uint256 r) {
        assembly ("memory-safe") {
            r := or(shl(8, wordIndex), bit)
        }
    }

    /// @notice Creates a new bitset with the given maximum size
    ///
    /// @param maxSize The maximum size of the bitset
    ///
    /// @return bitset The created bitset
    function create(uint256 maxSize) internal pure returns (uint256[] memory bitset) {
        bitset = new uint256[](_capacity(maxSize));
    }

    /// @notice Checks if the given value is contained in the bitset
    ///
    /// @param bitset The bitset to check
    /// @param value The value to search for
    ///
    /// @return _contains True if the value is contained in the bitset, false otherwise
    function contains(uint256[] memory bitset, uint256 value) internal pure returns (bool _contains) {
        (uint256 wordIndex, uint8 bit) = _bitOffset(value);
        if (wordIndex < bitset.length) {
            _contains = (bitset[wordIndex] & (1 << bit)) != 0;
        }
    }

    /// @notice Adds the given value to the bitset
    ///
    /// @param bitset The bitset to modify
    /// @param value The value to add
    ///
    /// @return The modified bitset
    function add(uint256[] memory bitset, uint256 value) internal pure returns (uint256[] memory) {
        (uint256 wordIndex, uint8 bit) = _bitOffset(value);
        bitset[wordIndex] |= (1 << bit);
        return bitset;
    }

    /// @notice Adds all elements from bitset b to bitset a
    ///
    /// @param a The destination bitset
    /// @param b The source bitset
    ///
    /// @return c The resulting bitset
    function addAll(uint256[] memory a, uint256[] memory b) internal pure returns (uint256[] memory c) {
        (uint256 min, uint256 max) = a.length < b.length ? (a.length, b.length) : (b.length, a.length);
        c = new uint256[](max);
        uint256 i;
        for (; i < min; ++i) {
            c[i] = a[i] | b[i];
        }
        // copy leftover elements from a
        for (; i < a.length; ++i) {
            c[i] = a[i];
        }
        // copy leftover elements from b
        for (; i < b.length; ++i) {
            c[i] = b[i];
        }
    }

    /// @notice Removes the given value from the bitset
    ///
    /// @param bitset The bitset to modify
    /// @param value The value to remove
    ///
    /// @return The modified bitset
    function remove(uint256[] memory bitset, uint256 value) internal pure returns (uint256[] memory) {
        (uint256 wordIndex, uint8 bit) = _bitOffset(value);
        bitset[wordIndex] &= ~(1 << bit);
        return bitset;
    }

    /// @notice Computes the size (number of set bits) of the bitset
    ///
    /// @param bitset The bitset to compute the size of
    ///
    /// @return count The number of set bits in the bitset
    function size(uint256[] memory bitset) internal pure returns (uint256 count) {
        for (uint256 i; i < bitset.length; ++i) {
            count += _countSetBits(bitset[i]);
        }
    }

    /// @dev Computes the word index and bit position for the given value
    ///
    /// @param value The value to compute the offsets for
    ///
    /// @return wordIndex The index of the word containing the value
    /// @return bit The bit position within the word
    function _bitOffset(uint256 value) private pure returns (uint256 wordIndex, uint8 bit) {
        assembly ("memory-safe") {
            wordIndex := shr(8, value)
            // mask bits that don't fit the first wordIndex's bits
            // n % 2^i = n & (2^i - 1)
            bit := and(value, 255)
        }
    }

    /// @dev Computes the number of words required to store the given maximum size
    ///
    /// @param maxSize The maximum size of the bitset
    ///
    /// @return words The number of words required
    function _capacity(uint256 maxSize) private pure returns (uint256 words) {
        // round up
        words = (maxSize + type(uint8).max) >> WORD_SHIFT;
    }

    /// @dev Counts the number of set bits in the given word using Brian Kernighan's algorithm
    ///
    /// @param x The word to count the set bits of
    ///
    /// @return count The number of set bits in the word
    function _countSetBits(uint256 x) private pure returns (uint256 count) {
        // Brian Kernighan's Algorithm
        // This algorithm counts the number of set bits in a word by repeatedly
        // clearing the least significant set bit until the word becomes zero.
        while (x != 0) {
            unchecked {
                // cannot overflow, x > 0
                x = x & (x - 1);
                ++count;
            }
        }
    }
}

File 6 of 18 : CurrencyLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

type Currency is address;

using {eq as ==, neq as !=} for Currency global;

function eq(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function neq(Currency currency, Currency other) pure returns (bool) {
    return !eq(currency, other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
/// @author Modified from Uniswap (https://github.com/Uniswap/v4-core/blob/main/src/types/Currency.sol)
library CurrencyLib {
    using SafeERC20 for IERC20;
    using CurrencyLib for Currency;

    /// @dev Currency wrapper for native currency
    Currency public constant NATIVE = Currency.wrap(address(0));

    /// @notice Thrown when a native transfer fails
    error NativeTransferFailed();

    /// @notice Thrown when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice Thrown when deposit amount exceeds current balance
    error AmountExceedsBalance();

    /// @notice Transfers currency
    ///
    /// @param currency Currency to transfer
    /// @param to Address of recipient
    /// @param amount Currency amount ot transfer
    function transfer(Currency currency, address to, uint256 amount) internal {
        if (amount == 0) return;
        // implementation from
        // https://github.com/transmissions11/solmate/blob/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/SafeTransferLib.sol

        bool success;
        if (currency.isNative()) {
            assembly {
                // Transfer the ETH and store if it succeeded or not.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }

            if (!success) revert NativeTransferFailed();
        } else {
            assembly {
                // We'll write our calldata to this slot below, but restore it later.
                let freeMemoryPointer := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because that's the total length of our calldata (4 + 32 * 2)
                        // Counterintuitively, this call() must be positioned after the or() in the
                        // surrounding and() because and() evaluates its arguments from right to left.
                        call(gas(), currency, 0, freeMemoryPointer, 68, 0, 32)
                    )
            }

            if (!success) revert ERC20TransferFailed();
        }
    }

    /// @notice Approves currency
    ///
    /// @param currency Currency to approve
    /// @param spender Address of spender
    /// @param amount Currency amount to approve
    function approve(Currency currency, address spender, uint256 amount) internal {
        if (isNative(currency)) return;
        IERC20(Currency.unwrap(currency)).forceApprove(spender, amount);
    }

    /// @notice Returns the balance of a given currency for a specific account
    ///
    /// @param currency The currency to check
    /// @param account The address of the account
    ///
    /// @return The balance of the specified currency for the given account
    function balanceOf(Currency currency, address account) internal view returns (uint256) {
        return currency.isNative() ? account.balance : IERC20(Currency.unwrap(currency)).balanceOf(account);
    }

    /// @notice Returns the balance of a given currency for this contract
    ///
    /// @param currency The currency to check
    ///
    /// @return The balance of the specified currency for this contract
    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        return currency.isNative() ? address(this).balance : IERC20(Currency.unwrap(currency)).balanceOf(address(this));
    }

    /// @notice Checks if the specified currency is the native currency
    ///
    /// @param currency The currency to check
    ///
    /// @return `true` if the specified currency is the native currency, `false` otherwise
    function isNative(Currency currency) internal pure returns (bool) {
        return currency == NATIVE;
    }
}

File 7 of 18 : AnatomyValidationLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;

import {IVault} from "../interfaces/IVault.sol";

import {BitSet} from "./BitSet.sol";
import {CurrencyLib, Currency} from "./CurrencyLib.sol";
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";
import {a160u96, A160U96Factory} from "../utils/a160u96.sol";

/// @title AnatomyValidationLib
/// @notice A library for validating the anatomy of a vault
library AnatomyValidationLib {
    using CurrencyLib for *;
    using FixedPointMathLib for uint256;
    using BitSet for uint256[];

    /// @dev Struct to hold the indexes of anatomy, new anatomy and withdrawal
    struct Indexes {
        uint256 anatomy;
        uint256 newAnatomy;
        uint256 withdrawal;
    }

    /// @notice Thrown when the currencies hash doesn't match the expected value
    error CurrenciesHashMismatch();

    /// @notice Thrown when the new anatomy contains an excess currency index
    /// @param currencyIndex The excess currency index
    error ExcessNewAnatomyCurrencyIndex(uint256 currencyIndex);

    /// @notice Thrown when a currency index is not found in the new anatomy
    /// @param currencyIndex The missing currency index
    error NewAnatomyCurrencyIndexNotFound(uint256 currencyIndex);

    /// @notice Thrown when the new anatomy currency count doesn't match the expected value
    /// @param expectedCount The expected count of new anatomy currencies
    error NewAnatomyCurrencyCountMismatch(uint256 expectedCount);

    /// @notice Thrown when the new anatomy currency index set size doesn't match the expected value
    /// @param expectedCount The expected size of the new anatomy currency index set
    error NewAnatomyCurrencyIndexSetSizeMismatch(uint256 expectedCount);

    /// @notice Thrown when a new anatomy currency doesn't match the expected value
    /// @param expectedCurrency The expected currency value
    error NewAnatomyCurrencyMismatch(a160u96 expectedCurrency);

    /// @notice Validates the anatomy of a vault
    ///
    /// @param unaccountedBalanceOf The mapping of unaccounted currency balances
    /// @param anatomyCurrencyIndexSet The index set of anatomy currencies
    /// @param currenciesHash The expected hash of currencies
    /// @param params The end rebalancing parameters
    function validate(
        mapping(Currency => uint96) storage unaccountedBalanceOf,
        uint256[] memory anatomyCurrencyIndexSet,
        bytes32 currenciesHash,
        IVault.EndRebalancingParams calldata params
    ) internal {
        Indexes memory indexes;
        bytes32 _currenciesHash;
        for (uint256 i; i < params.currencies.length; ++i) {
            Currency currency = params.currencies[i];

            _currenciesHash = keccak256(abi.encode(_currenciesHash, currency));

            uint96 balance = unaccountedBalanceOf[currency];
            if (balance != 0) delete unaccountedBalanceOf[currency];

            // If the currency is in the anatomy index set
            if (anatomyCurrencyIndexSet.contains(i)) {
                // Add new anatomy balance to the balance
                balance += uint96(params.lastKBalance.mulWadDown(params.anatomyCurrencies[indexes.anatomy].value()));

                // If the currency is in the withdrawals index set
                if (params.withdrawals.currencyIndexSet.contains(i)) {
                    // Subtract the withdrawal amount from the balance
                    balance -= params.withdrawals.amounts[indexes.withdrawal];

                    unchecked {
                        ++indexes.withdrawal;
                    }
                }

                unchecked {
                    ++indexes.anatomy;
                }
            }

            if (balance == 0) {
                // new anatomy shouldn't contain any currencies without balances
                if (params.newAnatomy.currencyIndexSet.contains(i)) revert ExcessNewAnatomyCurrencyIndex(i);
            } else {
                // new anatomy must contain all non-zero currency balances
                if (!params.newAnatomy.currencyIndexSet.contains(i)) revert NewAnatomyCurrencyIndexNotFound(i);

                a160u96 _currency = A160U96Factory.create(currency, balance);
                if (params.newAnatomy.currencies[indexes.newAnatomy] != _currency) {
                    // new anatomy currency must match the expected packed currency
                    revert NewAnatomyCurrencyMismatch(_currency);
                }

                unchecked {
                    // cannot overflow, new anatomy index < (old anatomy + updates)
                    ++indexes.newAnatomy;
                }
            }
        }

        // currencies hash must match the expected value
        // this is checked to verify that the currencies list
        // is in correct order, contains no duplicates and is complete
        if (_currenciesHash != currenciesHash) revert CurrenciesHashMismatch();

        // accumulated newAnatomy index must match the length of new anatomy currencies
        if (indexes.newAnatomy != params.newAnatomy.currencies.length) {
            revert NewAnatomyCurrencyCountMismatch(indexes.newAnatomy);
        }

        // new anatomy currency index set size must match the length of new anatomy currencies
        if (indexes.newAnatomy != params.newAnatomy.currencyIndexSet.size()) {
            revert NewAnatomyCurrencyIndexSetSizeMismatch(indexes.newAnatomy);
        }
    }
}

File 8 of 18 : FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, z)
            }

            // Goal was to get z*z*y within a small factor of x. More iterations could
            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
            // We ensured y >= 256 so that the relative difference between y and y+1 is small.
            // That's not possible if x < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.

            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.

            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.

            // There is no overflow risk here since y < 2^136 after the first branch above.
            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If x+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

File 9 of 18 : SafeCastLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Safe unsigned integer casting library that reverts on overflow.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
library SafeCastLib {
    function safeCastTo248(uint256 x) internal pure returns (uint248 y) {
        require(x < 1 << 248);

        y = uint248(x);
    }

    function safeCastTo240(uint256 x) internal pure returns (uint240 y) {
        require(x < 1 << 240);

        y = uint240(x);
    }

    function safeCastTo232(uint256 x) internal pure returns (uint232 y) {
        require(x < 1 << 232);

        y = uint232(x);
    }

    function safeCastTo224(uint256 x) internal pure returns (uint224 y) {
        require(x < 1 << 224);

        y = uint224(x);
    }

    function safeCastTo216(uint256 x) internal pure returns (uint216 y) {
        require(x < 1 << 216);

        y = uint216(x);
    }

    function safeCastTo208(uint256 x) internal pure returns (uint208 y) {
        require(x < 1 << 208);

        y = uint208(x);
    }

    function safeCastTo200(uint256 x) internal pure returns (uint200 y) {
        require(x < 1 << 200);

        y = uint200(x);
    }

    function safeCastTo192(uint256 x) internal pure returns (uint192 y) {
        require(x < 1 << 192);

        y = uint192(x);
    }

    function safeCastTo184(uint256 x) internal pure returns (uint184 y) {
        require(x < 1 << 184);

        y = uint184(x);
    }

    function safeCastTo176(uint256 x) internal pure returns (uint176 y) {
        require(x < 1 << 176);

        y = uint176(x);
    }

    function safeCastTo168(uint256 x) internal pure returns (uint168 y) {
        require(x < 1 << 168);

        y = uint168(x);
    }

    function safeCastTo160(uint256 x) internal pure returns (uint160 y) {
        require(x < 1 << 160);

        y = uint160(x);
    }

    function safeCastTo152(uint256 x) internal pure returns (uint152 y) {
        require(x < 1 << 152);

        y = uint152(x);
    }

    function safeCastTo144(uint256 x) internal pure returns (uint144 y) {
        require(x < 1 << 144);

        y = uint144(x);
    }

    function safeCastTo136(uint256 x) internal pure returns (uint136 y) {
        require(x < 1 << 136);

        y = uint136(x);
    }

    function safeCastTo128(uint256 x) internal pure returns (uint128 y) {
        require(x < 1 << 128);

        y = uint128(x);
    }

    function safeCastTo120(uint256 x) internal pure returns (uint120 y) {
        require(x < 1 << 120);

        y = uint120(x);
    }

    function safeCastTo112(uint256 x) internal pure returns (uint112 y) {
        require(x < 1 << 112);

        y = uint112(x);
    }

    function safeCastTo104(uint256 x) internal pure returns (uint104 y) {
        require(x < 1 << 104);

        y = uint104(x);
    }

    function safeCastTo96(uint256 x) internal pure returns (uint96 y) {
        require(x < 1 << 96);

        y = uint96(x);
    }

    function safeCastTo88(uint256 x) internal pure returns (uint88 y) {
        require(x < 1 << 88);

        y = uint88(x);
    }

    function safeCastTo80(uint256 x) internal pure returns (uint80 y) {
        require(x < 1 << 80);

        y = uint80(x);
    }

    function safeCastTo72(uint256 x) internal pure returns (uint72 y) {
        require(x < 1 << 72);

        y = uint72(x);
    }

    function safeCastTo64(uint256 x) internal pure returns (uint64 y) {
        require(x < 1 << 64);

        y = uint64(x);
    }

    function safeCastTo56(uint256 x) internal pure returns (uint56 y) {
        require(x < 1 << 56);

        y = uint56(x);
    }

    function safeCastTo48(uint256 x) internal pure returns (uint48 y) {
        require(x < 1 << 48);

        y = uint48(x);
    }

    function safeCastTo40(uint256 x) internal pure returns (uint40 y) {
        require(x < 1 << 40);

        y = uint40(x);
    }

    function safeCastTo32(uint256 x) internal pure returns (uint32 y) {
        require(x < 1 << 32);

        y = uint32(x);
    }

    function safeCastTo24(uint256 x) internal pure returns (uint24 y) {
        require(x < 1 << 24);

        y = uint24(x);
    }

    function safeCastTo16(uint256 x) internal pure returns (uint16 y) {
        require(x < 1 << 16);

        y = uint16(x);
    }

    function safeCastTo8(uint256 x) internal pure returns (uint8 y) {
        require(x < 1 << 8);

        y = uint8(x);
    }
}

File 10 of 18 : a160u96.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.23;

import {Currency} from "../libraries/CurrencyLib.sol";

type a160u96 is uint256;

using {addr, unpack, unpackRaw, currency, value, eq as ==, neq as !=} for a160u96 global;

error AddressMismatch(address, address);

function neq(a160u96 a, a160u96 b) pure returns (bool) {
    return !eq(a, b);
}

function eq(a160u96 a, a160u96 b) pure returns (bool) {
    return a160u96.unwrap(a) == a160u96.unwrap(b);
}

function currency(a160u96 packed) pure returns (Currency) {
    return Currency.wrap(addr(packed));
}

function addr(a160u96 packed) pure returns (address) {
    return address(uint160(a160u96.unwrap(packed)));
}

function value(a160u96 packed) pure returns (uint96) {
    return uint96(a160u96.unwrap(packed) >> 160);
}

function unpack(a160u96 packed) pure returns (Currency _curr, uint96 _value) {
    uint256 raw = a160u96.unwrap(packed);
    _curr = Currency.wrap(address(uint160(raw)));
    _value = uint96(raw >> 160);
}

function unpackRaw(a160u96 packed) pure returns (address _addr, uint96 _value) {
    uint256 raw = a160u96.unwrap(packed);
    _addr = address(uint160(raw));
    _value = uint96(raw >> 160);
}

library A160U96Factory {
    function create(address _addr, uint96 _value) internal pure returns (a160u96) {
        return a160u96.wrap((uint256(_value) << 160) | uint256(uint160(_addr)));
    }

    function create(Currency _currency, uint96 _value) internal pure returns (a160u96) {
        return create(Currency.unwrap(_currency), _value);
    }
}

File 11 of 18 : CurrencyRegistryLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;

import {Currency} from "./CurrencyLib.sol";

/// @title CurrencyRegistryLib
/// @notice A library for managing a registry of currencies
library CurrencyRegistryLib {
    /// @dev Represents a currency registry
    struct Registry {
        // Array of registered assets
        Currency[] currencies;
        // Hash of registry state
        bytes32 currenciesHash;
        // Registered flag for given currency
        mapping(Currency => bool) registered;
    }

    /// @notice Thrown when trying to register an already registered currency.
    /// @param currency The currency that is already registered
    error Registered(Currency currency);

    /// @notice Registers a new currency in the registry
    ///
    /// @param self The registry where the currency will be registered
    /// @param currency The currency to register
    ///
    /// @return newHash The new hash of the updated registry
    function registerCurrency(Registry storage self, Currency currency) internal returns (bytes32 newHash) {
        if (self.registered[currency]) revert Registered(currency);

        self.currencies.push(currency);
        newHash = keccak256(abi.encode(self.currenciesHash, currency));
        self.currenciesHash = newHash;
        self.registered[currency] = true;
    }
}

File 12 of 18 : Extsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

/// @title Extsload
/// @author Modified from RageTrade (https://github.com/RageTrade/core/blob/main/contracts/utils/Extsload.sol)
abstract contract Extsload {
    /// @notice Externally loads the value stored at the specified slot
    ///
    /// @param slot The slot to load the value from
    ///
    /// @return value The value stored at the specified slot
    function extsload(bytes32 slot) external view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := sload(slot)
        }
    }

    /// @notice Externally loads the values stored at the specified slots
    ///
    /// @param slots An array of slots to load the values from
    ///
    /// @return An array of values stored at the specified slots
    function extsload(bytes32[] memory slots) external view returns (bytes32[] memory) {
        assembly ("memory-safe") {
            let end := add(32, add(slots, mul(mload(slots), 32)))
            for { let ptr := add(slots, 32) } lt(ptr, end) { ptr := add(ptr, 32) } { mstore(ptr, sload(mload(ptr))) }
        }

        return slots;
    }
}

File 13 of 18 : Owned.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OwnershipTransferred(address indexed user, address indexed newOwner);

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function transferOwnership(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

File 14 of 18 : ReentrancyGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

File 15 of 18 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

File 16 of 18 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

File 17 of 18 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 18 of 18 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/phuture-v2-contracts/lib/@openzeppelin/contracts/",
    "chainlink/=lib/phuture-v2-contracts/lib/chainlink-brownie-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "layerzero/=lib/phuture-v2-contracts/lib/LayerZero/contracts/",
    "redstone/=lib/phuture-v2-contracts/lib/redstone-oracles-monorepo/packages/evm-connector/contracts/",
    "solmate/=lib/phuture-v2-contracts/lib/solmate/src/",
    "src/=lib/phuture-v2-contracts/src/",
    "sstore2/=lib/phuture-v2-contracts/lib/sstore2/contracts/",
    "@chainlink/=node_modules/@chainlink/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@openzeppelin/contracts-upgradeable/=lib/phuture-v2-contracts/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@redstone-finance/=node_modules/@redstone-finance/",
    "LayerZero/=lib/phuture-v2-contracts/lib/LayerZero/contracts/",
    "chainlink-brownie-contracts/=lib/phuture-v2-contracts/lib/chainlink-brownie-contracts/contracts/src/v0.6/vendor/@arbitrum/nitro-contracts/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/phuture-v2-contracts/lib/@openzeppelin/lib/erc4626-tests/",
    "openzeppelin-contracts-upgradeable/=lib/phuture-v2-contracts/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin/=lib/phuture-v2-contracts/lib/@openzeppelin/contracts/",
    "phuture-v2-contracts/=lib/phuture-v2-contracts/src/",
    "redstone-oracles-monorepo/=lib/phuture-v2-contracts/lib/",
    "solady/=lib/phuture-v2-contracts/lib/solady/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200,
    "details": {
      "constantOptimizer": true,
      "yul": true,
      "yulDetails": {
        "stackAllocation": true
      }
    }
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": false
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_messenger","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CurrenciesHashMismatch","type":"error"},{"inputs":[],"name":"ERC20TransferFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"currencyIndex","type":"uint256"}],"name":"ExcessNewAnatomyCurrencyIndex","type":"error"},{"inputs":[],"name":"Forbidden","type":"error"},{"inputs":[],"name":"HashMismatch","type":"error"},{"inputs":[],"name":"InvalidWithdrawal","type":"error"},{"inputs":[],"name":"NativeTransferFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedCount","type":"uint256"}],"name":"NewAnatomyCurrencyCountMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"currencyIndex","type":"uint256"}],"name":"NewAnatomyCurrencyIndexNotFound","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedCount","type":"uint256"}],"name":"NewAnatomyCurrencyIndexSetSizeMismatch","type":"error"},{"inputs":[{"internalType":"a160u96","name":"expectedCurrency","type":"uint256"}],"name":"NewAnatomyCurrencyMismatch","type":"error"},{"inputs":[],"name":"Rebalancing","type":"error"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"Registered","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Currency","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Consume","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Currency","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Donate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"snapshot","type":"uint256"},{"indexed":false,"internalType":"a160u96[]","name":"currencies","type":"uint256[]"}],"name":"FinishRebalancing","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"snapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"SnapshotTransfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"snapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"kBalance","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"currencyIndexSet","type":"uint256[]"},{"internalType":"uint96[]","name":"amounts","type":"uint96[]"}],"indexed":false,"internalType":"struct IVault.CurrencyWithdrawal","name":"withdrawals","type":"tuple"}],"name":"StartRebalancing","type":"event"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint96","name":"amount","type":"uint96"},{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"consume","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"donate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"extsload","outputs":[{"internalType":"bytes32","name":"value","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"slots","type":"bytes32[]"}],"name":"extsload","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"a160u96[]","name":"anatomyCurrencies","type":"uint256[]"},{"components":[{"internalType":"a160u96[]","name":"currencies","type":"uint256[]"},{"internalType":"uint256[]","name":"currencyIndexSet","type":"uint256[]"}],"internalType":"struct IVault.SnapshotAnatomy","name":"newAnatomy","type":"tuple"},{"components":[{"internalType":"uint256[]","name":"currencyIndexSet","type":"uint256[]"},{"internalType":"uint96[]","name":"amounts","type":"uint96[]"}],"internalType":"struct IVault.CurrencyWithdrawal","name":"withdrawals","type":"tuple"},{"internalType":"uint256","name":"lastKBalance","type":"uint256"},{"internalType":"Currency[]","name":"currencies","type":"address[]"}],"internalType":"struct IVault.EndRebalancingParams","name":"params","type":"tuple"}],"name":"finishRebalancingPhase","outputs":[{"internalType":"bytes32","name":"resultHash","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"kBalanceWads","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency[]","name":"currencies","type":"address[]"}],"name":"registerCurrencies","outputs":[{"components":[{"internalType":"Currency[]","name":"currencies","type":"address[]"},{"internalType":"bytes32","name":"currenciesHash","type":"bytes32"}],"internalType":"struct IVault.RegisterCurrenciesResult","name":"result","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_messenger","type":"address"}],"name":"setMessenger","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_orderBook","type":"address"}],"name":"setOrderBook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256[]","name":"currencyIndexSet","type":"uint256[]"},{"internalType":"uint96[]","name":"amounts","type":"uint96[]"}],"internalType":"struct IVault.CurrencyWithdrawal","name":"withdrawals","type":"tuple"}],"name":"startRebalancingPhase","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"kAmountWads","type":"uint256"}],"name":"transferLatestSnapshot","outputs":[{"internalType":"uint256","name":"snapshot","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"snapshot","type":"uint256"},{"internalType":"uint256","name":"kAmount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

Deployed Bytecode

0x6080604052600436101561001b575b361561001957600080fd5b005b60003560e01c80630ad58d2f146100fb578063133c2406146100f65780631e2eaeaf146100f15780635bf14422146100ec57806366285967146100e75780636f4342cb146100e25780637479dfa8146100dd5780638da5cb5b146100d85780639a1598c8146100d3578063a68a2997146100ce578063d1509c4c146100c9578063dbd035ff146100c4578063e2cbf4d4146100bf5763f2fde38b0361000e57610d64565b610cf7565b610c0c565b610b68565b610adf565b610a18565b6109ef565b61075b565b6106e1565b610682565b610587565b610568565b61020b565b610116565b6001600160a01b0381160361011157565b600080fd5b346101115760603660031901126101115760043560243560443561013981610100565b6101448233856115df565b60009283526020916008602052604084209260405180948591602082549182815201918852602088209388905b8282106101f15750505061018792500384610a9f565b825192845b848110610197578580f35b806001600160601b036101d06101c76101b260019587610e1d565b516001600160a01b0381169160a09190911c90565b90921686611cd7565b86816101e0575b5050500161018c565b6101e992611662565b3880866101d7565b855484526001958601958995509381019390910190610171565b346101115760031960203682018113610111576004918235916001600160401b0383116101115760a083850192843603011261011157600354610256906001600160a01b03166116f5565b60025460ff169182156105575784549261027a846000526009602052604060002090565b54946102896044820184610e36565b96604096875198896102a48882019260648701359084610f13565b03996102b8601f199b8c8101835282610a9f565b51902003610549576000198601906102da826000526009602052604060002090565b546103096102fd6102eb8880610f2f565b8c939193519283918c83019586610f95565b038d8101835282610a9f565b5190200361053b5750868461048560fe6105379b968a60007f9fb8c3be7f8f68cf2f5c24f5db3697cacd5cb1241a46a26e0cce3cc03069dbc760246103d09d9a6103786105259e6103676105129d600052600a602052604060002090565b61037360065491610fa9565b611751565b01976103aa61039061038a8b8b610e36565b80610f2f565b906103a5876000526008602052604060002090565b611012565b8a8c6103dc6103bc61038a8d8d610e36565b9290936103d0865194859283019687610f95565b03908101835282610a9f565b5190206103f3856000526009602052604060002090565b5561042261040d6104048b8b610e36565b8d810190610f2f565b906103a587600052600a602052604060002090565b61045c61044f61043c86600052600c602052604060002090565b3060009081526020919091526040902090565b670de0b6b3a76400009055565b51928352670de0b6b3a764000060208401523092604090a31660ff1660ff196002541617600255565b7ff4253f07dc7fa143515722038e1d56ecbbdc6f717b9556772ebc8cb012b4545f6104b361038a8484610e36565b906104c38c519283928d84611099565b0390a16105076104ed61038a6104e56104dc8686610e36565b88810190610f2f565b959094610e36565b9290936104f8610ac0565b9a468c52878c015236916110b0565b8989015236916110b0565b6060860152855193849182019586611132565b51902090519081529081906020820190565b0390f35b8751633f4d605360e01b8152fd5b8651633f4d605360e01b8152fd5b6040516370e0699160e11b81528590fd5b3461011157602036600319011261011157602060043554604051908152f35b346101115760408060031936011261011157600435906105a682610100565b6003546001600160a01b039260243592916105c29085166116f5565b60ff60025416610671576004546000818152600c602090815284822030835290526040902090939080549582870396871161066c579590556000848152600c60209081528482206001600160a01b0385168352815260409182902080548401905584518681529081019290925261053795929092169130917f9fb8c3be7f8f68cf2f5c24f5db3697cacd5cb1241a46a26e0cce3cc03069dbc79190a3519081529081906020820190565b610ffc565b81516370e0699160e11b8152600490fd5b346101115760203660031901126101115760043561069f81610100565b6000546001600160a01b0391906106b79083166116f5565b166001600160601b0360a01b6003541617600355600080f35b6001600160601b0381160361011157565b34610111576080366003190112610111576004356106fe81610100565b60243561070a816106d0565b6044359161071783610100565b606435926001600160401b039283851161011157366023860112156101115784600401359384116101115736602485870101116101115760246100199501926111a6565b346101115760031960203682011261011157600480356001600160401b038111610111578060040191604080948336030112610111576003546107a6906001600160a01b03166116f5565b60019360016107b760025460ff1690565b166109d257600494919454926107cb611aa3565b906107e86107e386600052600a602052604060002090565b610fa9565b9660009384865b6108c1575b7f089e12bc95016306d0e7026dafaaa6b3ba3813b37da7f83917dd42f234e6a8c589896108bc61083161043c83600052600c602052604060002090565b549261083e8430856115df565b61086f604051602081019061086681610858898786610f13565b03601f198101835282610a9f565b51902093611b1a565b92610884846000526009602052604060002090565b556108a7600161089660025460ff1690565b1760ff1660ff196002541617600255565b6108b083600455565b60405193849384611b29565b0390a1005b8498979698518110156109c9576108eb816108e66108df8b80610f2f565b36916110b0565b611cf8565b6108fc575b969795968601866107ef565b949861090f61090b8783611cf8565b1590565b6109bb5788808b6109ac88610992849f8e9f9d9e6109548e61094e6109498f9561094361096196602461097b990190610f2f565b906115c5565b611747565b95610e1d565b516001600160a01b031690565b6001600160a01b03166000908152600b6020526040902090565b9161098d83546001600160601b031690565b6114aa565b6001600160601b03166001600160601b0319825416179055565b0196919a5050979695976108f0565b505163c945242d60e01b8152fd5b869798506107f4565b6040516370e0699160e11b8152600490fd5b600091031261011157565b34610111576000366003190112610111576000546040516001600160a01b039091168152602090f35b3461011157602036600319011261011157600435610a3581610100565b600054610a4a906001600160a01b03166116f5565b60028054610100600160a81b03191660089290921b610100600160a81b0316919091179055005b634e487b7160e01b600052604160045260246000fd5b6001600160401b038111610a9a57604052565b610a71565b90601f801991011681019081106001600160401b03821117610a9a57604052565b60405190608082018281106001600160401b03821117610a9a57604052565b3461011157604036600319011261011157600435610afc81610100565b602435906001600160401b03908183116101115736602384011215610111578260040135918211610a9a5760405191610b3f601f8201601f191660200184610a9f565b808352366024828601011161011157602081600092602461001997018387013784010152611307565b34610111576040366003190112610111576020610bb0602435610b8a81610100565b600435600052600c835260406000209060018060a01b0316600052602052604060002090565b54604051908152f35b6001600160401b038111610a9a5760051b60200190565b602090602060408183019282815285518094520193019160005b828110610bf8575050505090565b835185529381019392810192600101610bea565b3461011157602080600319360112610111576004356001600160401b038111610111573660238201121561011157806004013590610c4982610bb9565b91610c576040519384610a9f565b8083526024602084019160051b8301019136831161011157602401905b828210610c9357610537610c87856114c5565b60405191829182610bd0565b81358152908401908401610c74565b6020808252825160408383015280516060840181905260808401949183019060005b818110610cda5750505090604091015191015290565b82516001600160a01b031687529584019591840191600101610cc4565b34610111576020366003190112610111576001600160401b036004358181116101115736602382011215610111578060040135918211610111573660248360051b8301011161011157610537916024610d589201610d536114f0565b61151a565b60405191829182610ca2565b3461011157602036600319011261011157600435610d8181610100565b6000805490916001600160a01b03908183163303610dd3571680916001600160601b0360a01b16178255337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b60405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606490fd5b634e487b7160e01b600052603260045260246000fd5b8051821015610e315760209160051b010190565b610e07565b903590603e1981360301821215610111570190565b9035601e19823603018112156101115701602081359101916001600160401b038211610111578160051b3603831361011157565b610e898180610e4b565b604080855284018190526001600160fb1b0381116101115760051b80916060850137820160806060820191610ec46020946020810190610e4b565b9386602060608794998603019101525201929160005b828110610ee8575050505090565b9091929382806001926001600160601b038835610f04816106d0565b16815201950193929101610eda565b929190610f2a602091604086526040860190610e7f565b930152565b903590601e198136030182121561011157018035906001600160401b03821161011157602001918160051b3603831361011157565b91908082526020809201929160005b828110610f81575050505090565b833585529381019392810192600101610f73565b916020610fa6938181520191610f64565b90565b90604051918281549182825260209260208301916000526020600020936000905b828210610fe257505050610fe092500383610a9f565b565b855484526001958601958895509381019390910190610fca565b634e487b7160e01b600052601160045260246000fd5b906001600160401b038311610a9a57600160401b8311610a9a57815483835580841061106e575b5061104a9091600052602060002090565b60005b83811061105a5750505050565b60019060208435940193818401550161104d565b60008360005284602060002092830192015b82811061108e575050611039565b818155600101611080565b604090610fa6949281528160208201520191610f64565b92916110bb82610bb9565b916110c96040519384610a9f565b829481845260208094019160051b810192831161011157905b8282106110ef5750505050565b813581529083019083016110e2565b90815180825260208080930193019160005b82811061111e575050505090565b835185529381019392810192600101611110565b91909160209081815260a08101918451818301528085015160408301526040850151926080606084015283518091528160c0840194019160005b82811061119257505050506060610fa693940151906080601f19828503019101526110fe565b83518652948101949281019260010161116c565b919290926002549060ff60018060a01b03926111c6848260081c166116f5565b16156109d2576001600160a01b0384166000908152600b6020526040902061120290610992876111fd83546001600160601b031690565b6112ba565b6112166001600160601b0386168286611662565b1693843b15610111576112439460009283604051809881958294630f4f8e6960e31b8452600484016112d3565b03925af19283156112b5577fb3762e93ec66871dd27c421b64edc79636345ff0a949cd04f7f8efce5bd4240e9361129c575b50604080516001600160a01b039290921682526001600160601b03929092166020820152a1565b806112a96112af92610a87565b806109e4565b38611275565b6112fb565b6001600160601b03918216908216039190821161066c57565b90918060409360208452816020850152848401376000828201840152601f01601f1916010190565b6040513d6000823e3d90fd5b600180540361142257600260018190555461132d9060081c6001600160a01b03166116f5565b61133681611b45565b91333b1561011157600061135e9160405180938192635456a73d60e11b835260048301611454565b038183335af180156112b5577f0553260a2e46b0577270d8992db02d30856ca880144c72d6e9503760946aef13936113ad926113a89261140f575b506113a384611b45565b61149d565b611bc0565b906113e26113cd8260018060a01b0316600052600b602052604060002090565b6109928461098d83546001600160601b031690565b604080516001600160a01b039290921682526001600160601b03929092166020820152a1610fe060018055565b806112a961141c92610a87565b38611399565b60405162461bcd60e51b815260206004820152600a6024820152695245454e5452414e435960b01b6044820152606490fd5b6020808252825181830181905290939260005b82811061148957505060409293506000838284010152601f8019910116010190565b818101860151848201604001528501611467565b9190820391821161066c57565b9190916001600160601b038080941691160191821161066c57565b805160051b8101602090602001602083015b8181106114e45750505090565b805154815282016114d7565b60405190604082018281106001600160401b03821117610a9a576040526000602083606081520152565b600054909290611532906001600160a01b03166116f5565b61153b81610bb9565b906115496040519283610a9f565b808252602091602081018260051b850190368211610111578486915b8383106115ab5750505050845260005b818110611583575050505090565b806115a161159c61159760019486896115c5565b6115d5565b611bd8565b8487015201611575565b819083356115b881610100565b8152019101908590611565565b9190811015610e315760051b0190565b35610fa681610100565b9091801561165d576000828152600c602090815260408083206001600160a01b038716845290915290209081549381850394851161066c57939091556040805192835260208301919091526000926001600160a01b0316917f9fb8c3be7f8f68cf2f5c24f5db3697cacd5cb1241a46a26e0cce3cc03069dbc79190a3565b505050565b821561165d576001600160a01b038181166116a1575050600080806116899481945af11590565b61168f57565b604051633d2cec6f60e21b8152600490fd5b602092600080936116dd966044946040519463a9059cbb60e01b865216600485015260248401525af1600051600114601f3d11163d1517161590565b6116e357565b604051633c9fd93960e21b8152600490fd5b6001600160a01b0316330361170657565b604051631dd2188d60e31b8152600490fd5b60405190606082018281106001600160401b03821117610a9a5760405260006040838281528260208201520152565b35610fa6816106d0565b929161175b611718565b60009260005b6080840161176f8186610f2f565b9050821015611a0357611597826109436117899388610f2f565b6040805160208082019889526001600160a01b03841682840152929784918891906117b78160608101610858565b519020986117e76117da8260018060a01b0316600052600b602052604060002090565b546001600160601b031690565b908c89611803866001600160601b03938487166119d357611cf8565b611919575b5082166118595750506108df8461182861183195966108e694018b610e36565b90810190610f2f565b61184057506001905b01611761565b516315e70c1f60e31b8152600481019190915260249150fd5b90919261090b61187f916108e66108df6118768a89018099610e36565b8a810190610f2f565b611901576001600160a01b03166001600160a01b031960a09290921b919091161791906118cc9083906118c6906118ba9061038a908c610e36565b968a01968751916115c5565b35141590565b6118e857505090816118e16001935160010190565b905261183a565b516317aa4f3d60e31b8152600481019190915260249150fd5b83516322c63c1360e01b815260048101879052602490fd5b9261195e61194861195461194861194161196496986119388b80610f2f565b909151916115c5565b3560a01c90565b6001600160601b031690565b6060880135611cd7565b906114aa565b91858a81860161197e886108e66108df61038a858c610e36565b611991575b50516001018b525089611808565b6109496119bd9396926119aa6104046119b7948b610e36565b98909101978851916115c5565b906112ba565b926119c9815160010190565b9052858a38611983565b6001600160a01b0386166000908152600b6020526040902080546bffffffffffffffffffffffff19169055611cf8565b5050919394509103611a91576020019081516020820190611a2761038a8385610e36565b90508103611a775750611a4f6108df611a45611a5493865195610e36565b6020810190610f2f565b611d2b565b03611a5c5750565b51604051635c9c0ac760e11b81526004810191909152602490fd5b60405163b705ebd160e01b81526004810191909152602490fd5b604051630b7758f760e41b8152600490fd5b6040519060055480835282602091602082019060056000527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0936000905b828210611af757505050610fe092500383610a9f565b85546001600160a01b031684526001958601958895509381019390910190611ae1565b600019811461066c5760010190565b610fa69392606092825260208201528160408201520190610e7f565b6000906001600160a01b031680611b5c5750504790565b6020602491604051928380926370a0823160e01b82523060048301525afa9182156112b5578092611b8c57505090565b9091506020823d602011611bb8575b81611ba860209383610a9f565b81010312611bb557505190565b80fd5b3d9150611b9b565b600160601b811015610111576001600160601b031690565b9060ff611bf78360018060a01b03166000526007602052604060002090565b5416611cb657600554600160401b811015610a9a576001810180600555811015610e315760056000527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db00180546001600160a01b0319166001600160a01b038416908117909155600654604080516020810192835290810192909252610fe091611ca99190611c898160608101610858565b519020938460065560018060a01b03166000526007602052604060002090565b805460ff19166001179055565b6040516305a6e69560e31b81526001600160a01b0383166004820152602490fd5b90670de0b6b3a7640000918160001904811182021583021561011157020490565b91906000928160081c9080518210611d0f57505050565b60019293945060ff91611d2191610e1d565b5192161b16151590565b600091908290815b8151851015611d7657611d468583610e1d565b518084915b611d645750810180911161066c57600190940193611d33565b60019091019060001981011680611d4b565b9350505056

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.