Skip to content
Verified contractPartialMIT

AdapterSnapshot

Address0xfc4802df5a2e48712db31c3f539bd0685eb42717
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,387,029
Creation transaction
0x806d7e7997…b41cb5f417

contracts/AdapterSnapshot.sol

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

import {PagedReader} from "./base/PagedReader.sol";

/// @notice Stateless adapter bindings and accounted cash at the externally pinned block.
contract AdapterSnapshot is PagedReader {
    struct Call {
        address target;
        bytes callData;
    }

    struct CallResult {
        bool success;
        bytes returnData;
    }

    /// @notice Each nibble declares fixed ABI words, or 15 for a cooperative collector.
    function read(uint256 formats, Call[] calldata calls) external view returns (CallResult[] memory results) {
        PageState memory state = _newPage(64, 0, 0);
        state.responseBudget = MAX_RESPONSE_BYTES;
        results = new CallResult[](calls.length);
        uint256 count;
        for (uint256 i; i < calls.length; ++i) {
            uint256 format = (formats >> (i * 4)) & 15;
            if (format == 0 && count != 0) break;
            uint256 expected = format < 15 ? format * 32 : 0;
            if (_pause(state, bytes(""), 128 + expected)) break;
            uint256 budget = MAX_RESPONSE_BYTES - state.encodedBytes - 128;
            bool success;
            bytes memory data;
            if (format == 15) {
                (success, data) = calls[i].target
                .staticcall(abi.encodeWithSignature("read(bytes,uint256)", calls[i].callData, budget));
                if (!success && count != 0 && data.length == 36 && bytes4(data) == ResponseBudgetTooSmall.selector) {
                    break;
                }
            } else {
                (success, data) = calls[i].target.staticcall(calls[i].callData);
                if (format != 0 && (!success || data.length != expected)) {
                    success = false;
                    data = bytes("");
                }
            }
            if (data.length > budget) revert ResponseTooLarge(data.length, budget);
            results[count++] = CallResult(success, data);
            state.encodedBytes += 128 + ((data.length + 31) & ~uint256(31));
            if (format == 0) break;
        }
        assembly ("memory-safe") { mstore(results, count) }
    }

    struct RootFacts {
        address vault;
        address oracle;
        address account;
        address asset;
        uint48 snapshotBlock;
        uint256 adapterIdle;
        uint256 accountIdle;
    }

    /// @notice Adapter bindings, locked liquidity and account idle balance in one call.
    /// @dev Binding/uint48 validation only. Header/feed freshness and NAV stay in Go.
    function rootFacts(address adapter) external view returns (RootFacts memory facts) {
        facts.vault = _address(_readUint(adapter, abi.encodeWithSignature("vault()")));
        facts.oracle = _address(_readUint(adapter, abi.encodeWithSignature("oracle()")));
        facts.account = _address(_readUint(adapter, abi.encodeWithSignature("account()")));
        if (
            facts.vault == address(0) || facts.oracle == address(0) || facts.account == address(0)
                || facts.account == adapter
        ) {
            revert InvalidInput();
        }
        facts.asset = _address(_readUint(facts.vault, abi.encodeWithSignature("asset()")));
        if (facts.asset == address(0)) revert InvalidInput();
        facts.snapshotBlock = uint48(_uint(_readUint(facts.oracle, abi.encodeWithSignature("snapshotBlock()")), 48));
        facts.adapterIdle = _readUint(adapter, abi.encodeWithSignature("lockedLiquidity()"));
        facts.accountIdle = _readUint(facts.asset, abi.encodeWithSignature("balanceOf(address)", facts.account));
    }
}

contracts/base/BoundedStaticReader.sol

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

import {LowLevelCall} from "openzeppelin/utils/LowLevelCall.sol";

/// @dev Static source calls and canonical scalar decoding.
abstract contract BoundedStaticReader {
    error InvalidInput();
    error SourceReadFailed(address target, bytes4 selector);

    function _readUint(address target, bytes memory input) internal view returns (uint256 value) {
        if (target == address(0) || input.length < 4) revert InvalidInput();
        (bool success, bytes32 first,) = LowLevelCall.staticcallReturn64Bytes(target, input);
        uint256 size = LowLevelCall.returnDataSize();
        if (!success || size != 32) revert SourceReadFailed(target, bytes4(input));
        return uint256(first);
    }

    function _probe(address target, bytes memory input, uint256 maxBytes)
        internal
        view
        returns (bool success, bytes memory data)
    {
        if (target == address(0) || input.length < 4) revert InvalidInput();
        (success, data) = target.staticcall(input);
        if (success && data.length > maxBytes) revert SourceReadFailed(target, bytes4(input));
    }

    function _address(uint256 value) internal pure returns (address) {
        if (value > type(uint160).max) revert InvalidInput();
        return address(uint160(value));
    }

    function _bool(uint256 value) internal pure returns (bool) {
        if (value > 1) revert InvalidInput();
        return value == 1;
    }

    function _uint(uint256 value, uint256 bits) internal pure returns (uint256) {
        if (bits < 256 && value >> bits != 0) revert InvalidInput();
        return value;
    }
}

contracts/base/PagedReader.sol

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

import {BoundedStaticReader} from "./BoundedStaticReader.sol";

/// @dev Paging is transport state; Go values the completed native facts.
abstract contract PagedReader is BoundedStaticReader {
    // 100,000-byte CRE Await envelope minus 106 protobuf bytes, rounded to ABI words.
    uint256 internal constant MAX_RESPONSE_BYTES = 99_872;
    uint256 internal constant DEFAULT_PAGE_BYTES = MAX_RESPONSE_BYTES - 192;

    error ResponseBudgetTooSmall(uint256 required);
    error ResponseTooLarge(uint256 actual, uint256 budget);

    struct PageState {
        bytes cursor;
        uint256 progress;
        uint256 checkpointGas;
        uint256 unitGas;
        uint256 encodedBytes;
        uint256 responseBudget;
        bytes nextCursor;
    }

    function page(bytes calldata snapshotCall, bytes calldata continuation) external view {
        if (msg.sender == address(this) || snapshotCall.length < 4) revert InvalidInput();
        _page(snapshotCall, continuation, DEFAULT_PAGE_BYTES);
    }

    /// @dev The outer batch supplies its remaining response capacity before acquisition.
    function read(bytes calldata snapshotCall, uint256 budget) external view {
        if (msg.sender == address(this) || snapshotCall.length < 4) revert InvalidInput();
        if (bytes4(snapshotCall[:4]) == this.page.selector) {
            (bytes memory original, bytes memory continuation) = abi.decode(snapshotCall[4:], (bytes, bytes));
            _page(original, continuation, budget);
        } else {
            _page(snapshotCall, bytes(""), budget);
        }
    }

    function _page(bytes memory snapshotCall, bytes memory continuation, uint256 budget) private view {
        (bool success, bytes memory result) =
            address(this).staticcall(abi.encodePacked(snapshotCall, continuation, uint256(continuation.length), budget));
        if (!success) {
            assembly ("memory-safe") { revert(add(result, 32), mload(result)) }
        }
        if (result.length > budget) revert ResponseTooLarge(result.length, budget);
        assembly ("memory-safe") { return(add(result, 32), mload(result)) }
    }

    function _newPage(uint256 terminalBytes, uint256 maxUnitBytes, uint256 maxCursorBytes)
        internal
        view
        returns (PageState memory state)
    {
        state.encodedBytes = terminalBytes;
        state.responseBudget = DEFAULT_PAGE_BYTES;
        if (msg.sender == address(this)) {
            uint256 length;
            uint256 budget;
            assembly ("memory-safe") {
                length := calldataload(sub(calldatasize(), 64))
                budget := calldataload(sub(calldatasize(), 32))
            }
            state.responseBudget = budget;
            bytes calldata continuation = msg.data[msg.data.length - 64 - length:msg.data.length - 64];
            if (length != 0) (state.progress, state.cursor) = abi.decode(continuation, (uint256, bytes));
        }
        uint256 required = terminalBytes + maxUnitBytes;
        if (maxUnitBytes != 0 || maxCursorBytes != 0) required += 96 + ((maxCursorBytes + 31) & ~uint256(31));
        if (required > state.responseBudget && state.responseBudget < DEFAULT_PAGE_BYTES) {
            revert ResponseBudgetTooSmall(required);
        }
    }

    // Always attempt the first indivisible unit. Reserve encoding/return memory
    // using actual output size and the greatest observed unit cost on this page.
    function _pause(PageState memory state, bytes memory cursor, uint256 nextUnitBytes) internal view returns (bool) {
        uint256 remaining = gasleft();
        if (state.checkpointGas != 0) {
            uint256 spent = state.checkpointGas > remaining ? state.checkpointGas - remaining : 0;
            if (spent > state.unitGas) state.unitGas = spent;
            uint256 free;
            assembly ("memory-safe") { free := mload(0x40) }
            uint256 encoded = state.encodedBytes;
            if (cursor.length != 0) encoded += 96 + ((cursor.length + 31) & ~uint256(31));
            uint256 words = (free + 2 * encoded + 31) / 32;
            uint256 current = (free + 31) / 32;
            uint256 memoryGas = 3 * (words - current) + (words * words - current * current) / 512;
            uint256 reserve = 40_000 + memoryGas + (encoded / 32) * 24;
            if (
                encoded + nextUnitBytes > state.responseBudget
                    || remaining <= reserve + (state.unitGas > 10_000 ? state.unitGas : 10_000)
            ) {
                state.nextCursor = abi.encode(state.progress, cursor);
                return true;
            }
        }
        state.checkpointGas = gasleft();
        ++state.progress;
        return false;
    }
}

lib/openzeppelin/contracts/utils/LowLevelCall.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "openzeppelin/=lib/openzeppelin/contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.