Skip to content
Verified contractExactBUSL-1.1

VPKeyRegistryLogic

Address0x0054f2ec75889bba6ee7ed784d883290ee9cb173
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,399,862
Creation transaction
0xb6bf3870e1…1e9251685d

src/protocol/lib/VPKeyRegistryLogic.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {BTCVaultRegistryTypes} from "./types/BTCVaultRegistryTypes.sol";
import {BIP322Utils} from "./helpers/BIP322Utils.sol";
import {BIP341} from "./taproot/BIP341.sol";
import {BTCProofOfPossession} from "./BTCProofOfPossession.sol";
import {EthProofOfPossession} from "./EthProofOfPossession.sol";
import {OpKeyVersionSearch} from "./OpKeyVersionSearch.sol";
import {Errors} from "./types/Errors.sol";
import {Constants} from "./types/Constants.sol";
import {BTCVaultTypes} from "../../lib/BTCVaultTypes.sol";
import {IApplicationRegistry} from "../../interfaces/IApplicationRegistry.sol";
import {IProtocolParams} from "../interfaces/IProtocolParams.sol";
import {IFeeEscrow} from "../interfaces/IFeeEscrow.sol";
import {Events} from "./types/Events.sol";

/// @title VPKeyRegistryLogic
/// @notice Vault-provider operation-key / payout versioned read + append logic, extracted
///         from BTCVaultRegistry to keep the registry under the EIP-170 runtime size limit.
/// @dev External (DELEGATECALL-linked) functions operate directly on the registry's VP key/payout
///      storage mappings passed by reference; emitted events therefore log with the registry as
///      emitter. Op-key v0 = `vaultProviders[provider].btcPubKey`, op-ETH v0 = the provider admin
///      address, payout v0 = BIP-86 P2TR of op-key v0.
library VPKeyRegistryLogic {
    /// @notice Emitted when a vault provider appends a new operation BTC key version
    event OperationBtcKeyVersionAdded(address indexed provider, uint16 indexed version, bytes32 opBtcKey, uint64 epoch);

    /// @notice Emitted when a vault provider appends a new operation ETH key version
    event OperationEthKeyVersionAdded(address indexed provider, uint16 indexed version, address opEthKey, uint64 epoch);

    /// @notice Emitted when a vault provider appends a new payout script version
    event PayoutScriptVersionAdded(address indexed provider, uint16 indexed version, bytes payoutScript, uint64 epoch);

    /// @notice External dependencies bundled for `register` to stay under the stack-slot limit
    struct RegisterDeps {
        IApplicationRegistry applicationRegistry;
        IProtocolParams protocolParams;
        IFeeEscrow feeEscrow;
    }

    /// @notice Value inputs for `register`, bundled into one memory struct so the external ABI decode
    ///         stays under the `--ir-minimum` coverage stack limit (mirrors PeginLogic.SubmitRequestParams).
    struct RegisterParams {
        bytes32 btcPubKeyXOnly;
        bytes btcPopSignature;
        address applicationEntryPoint;
        uint16 commissionBps;
        bytes payoutScriptPubKey;
        address opEthKey;
        bytes ethPopSignature;
        uint64 epoch;
    }

    // ========== Registration ==========

    /// @notice Register a vault provider: validate, store provider + payout v1 (+ optional op-ETH
    ///         v1), emit, forward the fee.
    /// @dev Runs in the registry's context via DELEGATECALL, so `msg.sender`/`msg.value`/`address(this)`
    ///      are the registry's. `epoch` is the bumped registry epoch (rolled back with the tx on revert).
    ///      A non-zero `opEthKey` bootstraps a distinct operation-ETH key as op-ETH v1 under the same
    ///      epoch bump, so the registrant admin never has to appear in relay traffic; `address(0)`
    ///      keeps the registrant as op-ETH v0 (pre-existing semantics).
    function register(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(bytes32 => address) storage btcKeyToProvider,
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion)) storage payoutScriptVersions,
        mapping(address => uint16) storage latestPayoutScriptVersion,
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)) storage opEthKeyVersions,
        mapping(address => uint16) storage latestOpEthKeyVersion,
        RegisterDeps memory deps,
        RegisterParams memory params
    ) external {
        IApplicationRegistry applicationRegistry = deps.applicationRegistry;
        IProtocolParams protocolParams = deps.protocolParams;
        IFeeEscrow feeEscrow = deps.feeEscrow;
        bytes32 btcPubKeyXOnly = params.btcPubKeyXOnly;
        address applicationEntryPoint = params.applicationEntryPoint;
        uint16 commissionBps = params.commissionBps;
        bytes memory payoutScriptPubKey = params.payoutScriptPubKey;
        address opEthKey = params.opEthKey;
        uint64 epoch = params.epoch;
        if (!BIP341.isValidXOnlyKey(btcPubKeyXOnly)) revert Errors.InvalidBTCPublicKey();
        if (applicationEntryPoint == address(0)) revert Errors.ZeroAddress();
        if (payoutScriptPubKey.length == 0) revert Errors.EmptyPayoutAddress();
        if (payoutScriptPubKey.length > Constants.MAX_PAYOUT_ADDRESS_LENGTH) revert Errors.PayoutAddressTooLong();

        // Validate commission against the hardcoded minimum and the protocol maximum
        if (commissionBps < Constants.MIN_VP_COMMISSION_BPS) {
            revert Errors.CommissionBelowMinimum(commissionBps, Constants.MIN_VP_COMMISSION_BPS);
        }
        uint16 maxCommission = protocolParams.getLatestOffchainParams().maxVpCommissionBps;
        if (commissionBps > maxCommission) revert Errors.CommissionAboveMaximum(commissionBps, maxCommission);

        // Validate application is registered and active
        if (
            applicationRegistry.getApplicationStatus(applicationEntryPoint)
                != IApplicationRegistry.ApplicationStatus.Active
        ) {
            revert Errors.ApplicationNotActive();
        }

        // Validate that universal challengers and application vault keepers are configured; without
        // them pegin ACKs could never complete.
        BTCVaultTypes.AddressBTCKeyPair[] memory challengers = protocolParams.getCurrentUniversalChallengers();
        if (challengers.length == 0) revert Errors.NoUniversalChallengersConfigured();
        BTCVaultTypes.AddressBTCKeyPair[] memory vaultKeepers =
            applicationRegistry.getCurrentVaultKeepers(applicationEntryPoint);
        if (vaultKeepers.length == 0) revert Errors.NoAppVaultKeepersConfigured();

        // VP ETH address and BTC key must not overlap with any current VK or UC.
        for (uint256 i = 0; i < challengers.length; i++) {
            if (challengers[i].ethAddress == msg.sender) revert Errors.ParticipantRoleOverlap();
            if (challengers[i].btcPubKey == btcPubKeyXOnly) revert Errors.ParticipantRoleOverlap();
        }
        for (uint256 i = 0; i < vaultKeepers.length; i++) {
            if (vaultKeepers[i].ethAddress == msg.sender) revert Errors.ParticipantRoleOverlap();
            if (vaultKeepers[i].btcPubKey == btcPubKeyXOnly) revert Errors.ParticipantRoleOverlap();
        }

        // Check registration fee from FeeEscrow
        if (msg.value != feeEscrow.vpRegistrationFee()) revert Errors.InvalidRegistrationFee();

        // BTC key and provider ETH address must each be unused
        if (btcKeyToProvider[btcPubKeyXOnly] != address(0)) revert Errors.BtcKeyAlreadyRegistered();
        if (vaultProviders[msg.sender].applicationEntryPoint != address(0)) revert Errors.EthKeyAlreadyRegistered();

        // Verify BTC Proof of Possession — proves provider owns the BTC private key
        bool popValid = BTCProofOfPossession.verify(
            params.btcPopSignature, btcPubKeyXOnly, msg.sender, BTCProofOfPossession.ACTION_REGISTER
        );
        if (!popValid) revert Errors.InvalidBTCProofOfPossession();

        // Store provider data
        vaultProviders[msg.sender] = BTCVaultRegistryTypes.VaultProvider({
            btcPubKey: btcPubKeyXOnly, applicationEntryPoint: applicationEntryPoint, commissionBps: commissionBps
        });
        btcKeyToProvider[btcPubKeyXOnly] = msg.sender;

        // Store the required payout as payout v1 (op-key v0 = btcPubKeyXOnly; op-ETH v0 = msg.sender).
        payoutScriptVersions[msg.sender][1] =
            BTCVaultRegistryTypes.PayoutScriptVersion({script: payoutScriptPubKey, epoch: epoch});
        latestPayoutScriptVersion[msg.sender] = 1;

        emit Events.VaultProviderRegistered(
            msg.sender, btcPubKeyXOnly, applicationEntryPoint, commissionBps, payoutScriptPubKey
        );
        emit PayoutScriptVersionAdded(msg.sender, 1, payoutScriptPubKey, epoch);

        // Optionally bootstrap a distinct operation-ETH key as op-ETH v1 under the same epoch.
        // Self-PoP by the NEW key mirrors `appendOperationEthKey`, so the registrant cannot claim
        // an address it does not control (one signature satisfying two required ACK slots).
        if (opEthKey != address(0)) {
            if (!EthProofOfPossession.verify(opEthKey, msg.sender, "", params.ethPopSignature)) {
                revert Errors.InvalidEthProofOfPossession();
            }
            opEthKeyVersions[msg.sender][1] = BTCVaultRegistryTypes.OpEthKeyVersion({key: opEthKey, epoch: epoch});
            latestOpEthKeyVersion[msg.sender] = 1;
            emit OperationEthKeyVersionAdded(msg.sender, 1, opEthKey, epoch);
        }

        // Forward the registration fee to FeeEscrow (claimable by the protocol treasury)
        if (msg.value > 0) {
            (bool success,) = address(feeEscrow).call{value: msg.value}("");
            if (!success) revert Errors.TransferFailed();
        }
    }

    // ========== Operation key / payout setters ==========

    /// @notice Append a new VP operation BTC key version (admin-gated, new-key self-PoP, VP-unique)
    /// @dev `caller` is the VP admin (the `vaultProviders` record key); `epoch` is the bumped registry epoch.
    ///      Rejects a key already owned by another VP (intra-role) or present in the VP's current app VK
    ///      roster / UC roster, mirroring the overlap checks enforced at registration.
    function appendOperationBtcKey(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(bytes32 => address) storage btcKeyToProvider,
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)) storage opBtcKeyVersions,
        mapping(address => uint16) storage latestOpBtcKeyVersion,
        IApplicationRegistry applicationRegistry,
        IProtocolParams protocolParams,
        address caller,
        bytes32 newOpBtcKey,
        bytes calldata btcPopSignature,
        uint64 epoch
    ) external {
        address app = vaultProviders[caller].applicationEntryPoint;
        if (app == address(0)) revert Errors.VaultProviderNotRegistered();

        if (!BIP341.isValidXOnlyKey(newOpBtcKey)) revert Errors.InvalidBTCPublicKey();

        // Intra-role uniqueness: the new key must not already belong to a DIFFERENT VP. A VP may
        // re-use one of its own prior keys (rollback) — that appends a new version, it does not
        // free the key for anyone else.
        address keyOwner = btcKeyToProvider[newOpBtcKey];
        if (keyOwner != address(0) && keyOwner != caller) revert Errors.BtcKeyAlreadyRegistered();

        // Current-roster overlap: reject a key held by a current VK (this app) or UC.
        BTCVaultTypes.AddressBTCKeyPair[] memory vaultKeepers = applicationRegistry.getCurrentVaultKeepers(app);
        for (uint256 i = 0; i < vaultKeepers.length; i++) {
            if (vaultKeepers[i].btcPubKey == newOpBtcKey) revert Errors.ParticipantRoleOverlap();
        }
        BTCVaultTypes.AddressBTCKeyPair[] memory challengers = protocolParams.getCurrentUniversalChallengers();
        for (uint256 i = 0; i < challengers.length; i++) {
            if (challengers[i].btcPubKey == newOpBtcKey) revert Errors.ParticipantRoleOverlap();
        }

        // Self-PoP against the NEW key, owned by the VP admin (caller).
        bool popValid = BTCProofOfPossession.verifyWithPayload(
            btcPopSignature,
            newOpBtcKey,
            caller,
            BTCProofOfPossession.ACTION_SET_OPERATION_BTC_KEY,
            abi.encodePacked(newOpBtcKey)
        );
        if (!popValid) revert Errors.InvalidBTCProofOfPossession();

        uint16 latest = latestOpBtcKeyVersion[caller];
        if (latest == type(uint16).max) revert Errors.OperationKeyVersionOverflow();
        uint16 newVersion = latest + 1;

        latestOpBtcKeyVersion[caller] = newVersion;
        opBtcKeyVersions[caller][newVersion] = BTCVaultRegistryTypes.OpBtcKeyVersion({key: newOpBtcKey, epoch: epoch});
        btcKeyToProvider[newOpBtcKey] = caller;

        emit OperationBtcKeyVersionAdded(caller, newVersion, newOpBtcKey, epoch);
    }

    /// @notice Append a new VP operation ETH key version (admin-gated, no PoP)
    /// @dev `caller` is the VP admin (the `vaultProviders` record key) and the op-ETH v0.
    function appendOperationEthKey(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)
        ) storage opEthKeyVersions,
        mapping(address => uint16) storage latestOpEthKeyVersion,
        address caller,
        address newOpEthKey,
        bytes calldata ethPopSignature,
        uint64 epoch
    ) external {
        if (vaultProviders[caller].applicationEntryPoint == address(0)) {
            revert Errors.VaultProviderNotRegistered();
        }
        if (newOpEthKey == address(0)) revert Errors.ZeroAddress();

        // Self-PoP against the NEW op-ETH key, owned by the VP admin (caller).
        if (!EthProofOfPossession.verify(newOpEthKey, caller, "", ethPopSignature)) {
            revert Errors.InvalidEthProofOfPossession();
        }

        uint16 latest = latestOpEthKeyVersion[caller];
        if (latest == type(uint16).max) revert Errors.OperationKeyVersionOverflow();
        uint16 newVersion = latest + 1;

        latestOpEthKeyVersion[caller] = newVersion;
        opEthKeyVersions[caller][newVersion] = BTCVaultRegistryTypes.OpEthKeyVersion({key: newOpEthKey, epoch: epoch});

        emit OperationEthKeyVersionAdded(caller, newVersion, newOpEthKey, epoch);
    }

    /// @notice Append a new VP payout script version (admin-gated, no PoP)
    function appendPayoutScript(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address
                => mapping(
                uint16 => BTCVaultRegistryTypes.PayoutScriptVersion
            )
        ) storage payoutScriptVersions,
        mapping(address => uint16) storage latestPayoutScriptVersion,
        address caller,
        bytes calldata newPayoutScript,
        uint64 epoch
    ) external {
        if (vaultProviders[caller].applicationEntryPoint == address(0)) {
            revert Errors.VaultProviderNotRegistered();
        }
        if (newPayoutScript.length == 0) revert Errors.EmptyPayoutAddress();
        if (newPayoutScript.length > Constants.MAX_PAYOUT_ADDRESS_LENGTH) revert Errors.PayoutAddressTooLong();

        uint16 latest = latestPayoutScriptVersion[caller];
        if (latest == type(uint16).max) revert Errors.OperationKeyVersionOverflow();
        uint16 newVersion = latest + 1;

        latestPayoutScriptVersion[caller] = newVersion;
        payoutScriptVersions[caller][newVersion] =
            BTCVaultRegistryTypes.PayoutScriptVersion({script: newPayoutScript, epoch: epoch});

        emit PayoutScriptVersionAdded(caller, newVersion, newPayoutScript, epoch);
    }

    // ========== Operation BTC key ==========

    /// @notice Operation BTC key at a specific version (v0 = registration key)
    function operationBtcKeyByVersion(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)
        ) storage opBtcKeyVersions,
        address provider,
        uint16 version
    ) external view returns (bytes32) {
        if (version == 0) return vaultProviders[provider].btcPubKey;
        return opBtcKeyVersions[provider][version].key;
    }

    /// @notice Current (latest) operation BTC key
    function currentOperationBtcKey(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)
        ) storage opBtcKeyVersions,
        mapping(address => uint16) storage latestOpBtcKeyVersion,
        address provider
    ) external view returns (bytes32) {
        uint16 latest = latestOpBtcKeyVersion[provider];
        if (latest == 0) return vaultProviders[provider].btcPubKey;
        return opBtcKeyVersions[provider][latest].key;
    }

    /// @notice Operation BTC key bonded at `epoch`: latest version whose epoch <= bonded epoch, else v0
    function operationBtcKeyAtEpoch(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)
        ) storage opBtcKeyVersions,
        mapping(address => uint16) storage latestOpBtcKeyVersion,
        address provider,
        uint64 epoch
    ) public view returns (bytes32) {
        uint16 v = OpKeyVersionSearch.findAtEpoch(opBtcKeyVersions[provider], latestOpBtcKeyVersion[provider], epoch);
        if (v == 0) return vaultProviders[provider].btcPubKey;
        return opBtcKeyVersions[provider][v].key;
    }

    // ========== Operation ETH key ==========

    /// @notice Operation ETH key at a specific version (v0 = provider admin)
    function operationEthKeyByVersion(
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)) storage opEthKeyVersions,
        address provider,
        uint16 version
    ) external view returns (address) {
        if (version == 0) return provider;
        return opEthKeyVersions[provider][version].key;
    }

    /// @notice Current (latest) operation ETH key
    function currentOperationEthKey(
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)) storage opEthKeyVersions,
        mapping(address => uint16) storage latestOpEthKeyVersion,
        address provider
    ) external view returns (address) {
        uint16 latest = latestOpEthKeyVersion[provider];
        if (latest == 0) return provider;
        return opEthKeyVersions[provider][latest].key;
    }

    /// @notice Operation ETH key bonded at `epoch`: latest version whose epoch <= bonded epoch, else v0
    function operationEthKeyAtEpoch(
        mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)) storage opEthKeyVersions,
        mapping(address => uint16) storage latestOpEthKeyVersion,
        address provider,
        uint64 epoch
    ) external view returns (address) {
        uint16 v = OpKeyVersionSearch.findAtEpoch(opEthKeyVersions[provider], latestOpEthKeyVersion[provider], epoch);
        if (v == 0) return provider;
        return opEthKeyVersions[provider][v].key;
    }

    // ========== Payout script ==========

    /// @notice Payout script at a specific version (v0 = BIP-86 of op-key v0)
    function payoutScriptByVersion(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion)
        ) storage payoutScriptVersions,
        address provider,
        uint16 version
    ) external view returns (bytes memory) {
        if (version == 0) return bip86DefaultPayout(vaultProviders[provider].btcPubKey);
        return payoutScriptVersions[provider][version].script;
    }

    /// @notice Current (latest) payout script (BIP-86 default when none set)
    function currentPayoutScript(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion)
        ) storage payoutScriptVersions,
        mapping(address => uint16) storage latestPayoutScriptVersion,
        address provider
    ) external view returns (bytes memory) {
        uint16 latest = latestPayoutScriptVersion[provider];
        if (latest == 0) return bip86DefaultPayout(vaultProviders[provider].btcPubKey);
        return payoutScriptVersions[provider][latest].script;
    }

    /// @notice Payout script bonded at `epoch`: latest version whose epoch <= bonded epoch, else BIP-86 of v0 op-key
    function payoutScriptAtEpoch(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)
        ) storage opBtcKeyVersions,
        mapping(address => uint16) storage latestOpBtcKeyVersion,
        mapping(
            address => mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion)
        ) storage payoutScriptVersions,
        mapping(address => uint16) storage latestPayoutScriptVersion,
        address provider,
        uint64 epoch
    ) external view returns (bytes memory) {
        uint16 v = OpKeyVersionSearch.findAtEpoch(
            payoutScriptVersions[provider], latestPayoutScriptVersion[provider], epoch
        );
        if (v != 0) return payoutScriptVersions[provider][v].script;
        return bip86DefaultPayout(
            operationBtcKeyAtEpoch(vaultProviders, opBtcKeyVersions, latestOpBtcKeyVersion, provider, epoch)
        );
    }

    /// @notice BIP-86 P2TR default payout scriptPubKey for an operation BTC key v0:
    ///         0x5120 (OP_1 OP_PUSHBYTES_32) || taproot-tweaked output key. Migration default,
    ///         not reachable from registration (new registrations supply an explicit payout stored as v1).
    function bip86DefaultPayout(bytes32 opKeyV0) public pure returns (bytes memory) {
        return abi.encodePacked(uint8(0x51), uint8(0x20), BIP322Utils.taprootTweakPubKey(opKeyV0));
    }

    // ========== Commission + fee ==========

    /// @notice Update the VP admin's commission; mirrors `BTCVaultRegistry.updateVaultProviderCommission`.
    function updateCommission(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        IApplicationRegistry applicationRegistry,
        IProtocolParams protocolParams,
        address caller,
        uint16 newCommissionBps
    ) external {
        address app = vaultProviders[caller].applicationEntryPoint;
        if (app == address(0)) revert Errors.VaultProviderNotRegistered();
        if (applicationRegistry.getApplicationStatus(app) != IApplicationRegistry.ApplicationStatus.Active) {
            revert Errors.ApplicationNotActive();
        }
        if (vaultProviders[caller].commissionBps == newCommissionBps) revert Errors.CommissionUnchanged();

        if (newCommissionBps < Constants.MIN_VP_COMMISSION_BPS) {
            revert Errors.CommissionBelowMinimum(newCommissionBps, Constants.MIN_VP_COMMISSION_BPS);
        }
        uint16 maxCommission = protocolParams.getLatestOffchainParams().maxVpCommissionBps;
        if (newCommissionBps > maxCommission) revert Errors.CommissionAboveMaximum(newCommissionBps, maxCommission);

        vaultProviders[caller].commissionBps = newCommissionBps;
        emit Events.VaultProviderCommissionUpdated(caller, newCommissionBps);
    }

    /// @notice Required pegin fee for `vaultProvider`; mirrors `BTCVaultRegistry._getPegInFee`.
    function pegInFee(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        IApplicationRegistry applicationRegistry,
        IProtocolParams protocolParams,
        IFeeEscrow feeEscrow,
        address vaultProvider
    ) external view returns (uint256 totalFee) {
        address applicationEntryPoint = vaultProviders[vaultProvider].applicationEntryPoint;
        if (applicationEntryPoint == address(0)) revert Errors.ZeroAddress();

        BTCVaultTypes.AddressBTCKeyPair[] memory universalChallengers = protocolParams.getCurrentUniversalChallengers();
        BTCVaultTypes.AddressBTCKeyPair[] memory appVaultKeepers =
            applicationRegistry.getCurrentVaultKeepers(applicationEntryPoint);

        totalFee = feeEscrow.getRequiredFee(universalChallengers.length, appVaultKeepers.length);
    }

    // ========== Participant overlap reads ==========

    /// @notice Whether `account` overlaps any current participant role; mirrors `BTCVaultRegistry.isParticipant`.
    function isParticipant(
        mapping(address => BTCVaultRegistryTypes.VaultProvider) storage vaultProviders,
        IApplicationRegistry applicationRegistry,
        IProtocolParams protocolParams,
        address account,
        address appEntryPoint
    ) external view returns (bool isVP, bool isVK, bool isUC) {
        isVP = vaultProviders[account].applicationEntryPoint != address(0);
        isVK = applicationRegistry.isVaultKeeper(appEntryPoint, account);

        BTCVaultTypes.AddressBTCKeyPair[] memory challengers = protocolParams.getCurrentUniversalChallengers();
        for (uint256 i = 0; i < challengers.length; i++) {
            if (challengers[i].ethAddress == account) {
                isUC = true;
                break;
            }
        }
    }

    /// @notice Whether `btcKey` overlaps any current participant role; mirrors `isParticipantByBtcKey`.
    function isParticipantByBtcKey(
        mapping(bytes32 => address) storage btcKeyToProvider,
        IApplicationRegistry applicationRegistry,
        IProtocolParams protocolParams,
        bytes32 btcKey,
        address appEntryPoint
    ) external view returns (bool isVP, bool isVK, bool isUC) {
        isVP = btcKeyToProvider[btcKey] != address(0);

        BTCVaultTypes.AddressBTCKeyPair[] memory vaultKeepers =
            applicationRegistry.getCurrentVaultKeepers(appEntryPoint);
        for (uint256 i = 0; i < vaultKeepers.length; i++) {
            if (vaultKeepers[i].btcPubKey == btcKey) {
                isVK = true;
                break;
            }
        }

        BTCVaultTypes.AddressBTCKeyPair[] memory challengers = protocolParams.getCurrentUniversalChallengers();
        for (uint256 i = 0; i < challengers.length; i++) {
            if (challengers[i].btcPubKey == btcKey) {
                isUC = true;
                break;
            }
        }
    }
}

lib/elliptic-curve-solidity/contracts/EllipticCurve.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 ** @title Elliptic Curve Library
 ** @dev Library providing arithmetic operations over elliptic curves.
 ** This library does not check whether the inserted points belong to the curve
 ** `isOnCurve` function should be used by the library user to check the aforementioned statement.
 ** @author Witnet Foundation
 */
library EllipticCurve {
    // Pre-computed constant for 2 ** 255
    uint256 private constant U255_MAX_PLUS_1 =
        57896044618658097711785492504343953926634992332820282019728792003956564819968;

    /// @dev Modular euclidean inverse of a number (mod p).
    /// @param _x The number
    /// @param _pp The modulus
    /// @return q such that x*q = 1 (mod _pp)
    function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
        require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
        uint256 q = 0;
        uint256 newT = 1;
        uint256 r = _pp;
        uint256 t;
        while (_x != 0) {
            t = r / _x;
            (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
            (r, _x) = (_x, r - t * _x);
        }

        return q;
    }

    /// @dev Modular exponentiation, b^e % _pp.
    /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
    /// @param _base base
    /// @param _exp exponent
    /// @param _pp modulus
    /// @return r such that r = b**e (mod _pp)
    function expMod(
            uint256 _base,
            uint256 _exp,
            uint256 _pp
        )
        internal pure
        returns (uint256) 
    {
        require(_pp != 0, "EllipticCurve: modulus is zero");

        if (_base == 0) return 0;
        if (_exp == 0) return 1;

        uint256 r = 1;
        uint256 bit = U255_MAX_PLUS_1;
        assembly {
            for {

            } gt(bit, 0) {

            } {
                r := mulmod(
                    mulmod(r, r, _pp),
                    exp(_base, iszero(iszero(and(_exp, bit)))),
                    _pp
                )
                r := mulmod(
                    mulmod(r, r, _pp),
                    exp(_base, iszero(iszero(and(_exp, div(bit, 2))))),
                    _pp
                )
                r := mulmod(
                    mulmod(r, r, _pp),
                    exp(_base, iszero(iszero(and(_exp, div(bit, 4))))),
                    _pp
                )
                r := mulmod(
                    mulmod(r, r, _pp),
                    exp(_base, iszero(iszero(and(_exp, div(bit, 8))))),
                    _pp
                )
                bit := div(bit, 16)
            }
        }

        return r;
    }

    /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
    /// @param _x coordinate x
    /// @param _y coordinate y
    /// @param _z coordinate z
    /// @param _pp the modulus
    /// @return (x', y') affine coordinates
    function toAffine(
            uint256 _x,
            uint256 _y,
            uint256 _z,
            uint256 _pp
        )
        internal pure 
        returns (uint256, uint256) 
    {
        uint256 zInv = invMod(_z, _pp);
        uint256 zInv2 = mulmod(zInv, zInv, _pp);
        uint256 x2 = mulmod(_x, zInv2, _pp);
        uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);

        return (x2, y2);
    }

    /// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
    /// @param _prefix parity byte (0x02 even, 0x03 odd)
    /// @param _x coordinate x
    /// @param _aa constant of curve
    /// @param _bb constant of curve
    /// @param _pp the modulus
    /// @return y coordinate y
    function deriveY(
            uint8 _prefix,
            uint256 _x,
            uint256 _aa,
            uint256 _bb,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256) 
    {
        require(
            _prefix == 0x02 || _prefix == 0x03,
            "EllipticCurve:innvalid compressed EC point prefix"
        );

        // x^3 + ax + b
        uint256 y2 = addmod(
            mulmod(_x, mulmod(_x, _x, _pp), _pp),
            addmod(mulmod(_x, _aa, _pp), _bb, _pp),
            _pp
        );
        y2 = expMod(y2, (_pp + 1) / 4, _pp);
        // uint256 cmp = yBit ^ y_ & 1;
        uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;

        return y;
    }

    /// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
    /// @param _x coordinate x of P1
    /// @param _y coordinate y of P1
    /// @param _aa constant of curve
    /// @param _bb constant of curve
    /// @param _pp the modulus
    /// @return true if x,y in the curve, false else
    function isOnCurve(
            uint _x,
            uint _y,
            uint _aa,
            uint _bb,
            uint _pp
        ) 
        internal pure 
        returns (bool) 
    {
        if (0 == _x || _x >= _pp || 0 == _y || _y >= _pp) {
            return false;
        }
        // y^2
        uint lhs = mulmod(_y, _y, _pp);
        // x^3
        uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
        if (_aa != 0) {
            // x^3 + a*x
            rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
        }
        if (_bb != 0) {
            // x^3 + a*x + b
            rhs = addmod(rhs, _bb, _pp);
        }

        return lhs == rhs;
    }

    /// @dev Calculate inverse (x, -y) of point (x, y).
    /// @param _x coordinate x of P1
    /// @param _y coordinate y of P1
    /// @param _pp the modulus
    /// @return (x, -y)
    function ecInv(
            uint256 _x,
            uint256 _y,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256) 
    {
        return (_x, (_pp - _y) % _pp);
    }

    /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
    /// @param _x1 coordinate x of P1
    /// @param _y1 coordinate y of P1
    /// @param _x2 coordinate x of P2
    /// @param _y2 coordinate y of P2
    /// @param _aa constant of the curve
    /// @param _pp the modulus
    /// @return (qx, qy) = P1+P2 in affine coordinates
    function ecAdd(
            uint256 _x1,
            uint256 _y1,
            uint256 _x2,
            uint256 _y2,
            uint256 _aa,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256) 
    {
        uint x = 0;
        uint y = 0;
        uint z = 0;

        // Double if x1==x2 else add
        if (_x1 == _x2) {
            // y1 = -y2 mod p
            if (addmod(_y1, _y2, _pp) == 0) {
                return (0, 0);
            } else {
                // P1 = P2
                (x, y, z) = jacDouble(_x1, _y1, 1, _aa, _pp);
            }
        } else {
            (x, y, z) = jacAdd(_x1, _y1, 1, _x2, _y2, 1, _pp);
        }
        // Get back to affine
        return toAffine(x, y, z, _pp);
    }

    /// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
    /// @param _x1 coordinate x of P1
    /// @param _y1 coordinate y of P1
    /// @param _x2 coordinate x of P2
    /// @param _y2 coordinate y of P2
    /// @param _aa constant of the curve
    /// @param _pp the modulus
    /// @return (qx, qy) = P1-P2 in affine coordinates
    function ecSub(
            uint256 _x1,
            uint256 _y1,
            uint256 _x2,
            uint256 _y2,
            uint256 _aa,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256) 
    {
        // invert square
        (uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
        // P1-square
        return ecAdd(_x1, _y1, x, y, _aa, _pp);
    }

    /// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
    /// @param _k scalar to multiply
    /// @param _x coordinate x of P1
    /// @param _y coordinate y of P1
    /// @param _aa constant of the curve
    /// @param _pp the modulus
    /// @return (qx, qy) = d*P in affine coordinates
    function ecMul(
            uint256 _k,
            uint256 _x,
            uint256 _y,
            uint256 _aa,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256) 
    {
        // Jacobian multiplication
        (uint256 x1, uint256 y1, uint256 z1) = jacMul(_k, _x, _y, 1, _aa, _pp);
        // Get back to affine
        return toAffine(x1, y1, z1, _pp);
    }

    /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
    /// @param _x1 coordinate x of P1
    /// @param _y1 coordinate y of P1
    /// @param _z1 coordinate z of P1
    /// @param _x2 coordinate x of square
    /// @param _y2 coordinate y of square
    /// @param _z2 coordinate z of square
    /// @param _pp the modulus
    /// @return (qx, qy, qz) P1+square in Jacobian
    function jacAdd(
            uint256 _x1,
            uint256 _y1,
            uint256 _z1,
            uint256 _x2,
            uint256 _y2,
            uint256 _z2,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256, uint256) 
    {
        if (_x1 == 0 && _y1 == 0) return (_x2, _y2, _z2);
        if (_x2 == 0 && _y2 == 0) return (_x1, _y1, _z1);

        // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
        uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
        zs[0] = mulmod(_z1, _z1, _pp);
        zs[1] = mulmod(_z1, zs[0], _pp);
        zs[2] = mulmod(_z2, _z2, _pp);
        zs[3] = mulmod(_z2, zs[2], _pp);

        // u1, s1, u2, s2
        zs = [
            mulmod(_x1, zs[2], _pp),
            mulmod(_y1, zs[3], _pp),
            mulmod(_x2, zs[0], _pp),
            mulmod(_y2, zs[1], _pp)
        ];

        // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
        require(
            zs[0] != zs[2] || zs[1] != zs[3],
            "Use jacDouble function instead"
        );

        uint[4] memory hr;
        //h
        hr[0] = addmod(zs[2], _pp - zs[0], _pp);
        //r
        hr[1] = addmod(zs[3], _pp - zs[1], _pp);
        //h^2
        hr[2] = mulmod(hr[0], hr[0], _pp);
        // h^3
        hr[3] = mulmod(hr[2], hr[0], _pp);
        // qx = -h^3  -2u1h^2+r^2
        uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
        qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
        // qy = -s1*z1*h^3+r(u1*h^2 -x^3)
        uint256 qy = mulmod(
            hr[1],
            addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp),
            _pp
        );
        qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
        // qz = h*z1*z2
        uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
        return (qx, qy, qz);
    }

    /// @dev Doubles a points (x, y, z).
    /// @param _x coordinate x of P1
    /// @param _y coordinate y of P1
    /// @param _z coordinate z of P1
    /// @param _aa the a scalar in the curve equation
    /// @param _pp the modulus
    /// @return (qx, qy, qz) 2P in Jacobian
    function jacDouble(
            uint256 _x,
            uint256 _y,
            uint256 _z,
            uint256 _aa,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256, uint256) 
    {
        if (_z == 0) return (_x, _y, _z);

        // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
        // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
        // x, y, z at this point represent the squares of _x, _y, _z
        uint256 x = mulmod(_x, _x, _pp); //x1^2
        uint256 y = mulmod(_y, _y, _pp); //y1^2
        uint256 z = mulmod(_z, _z, _pp); //z1^2

        // s
        uint s = mulmod(4, mulmod(_x, y, _pp), _pp);
        // m
        uint m = addmod(
            mulmod(3, x, _pp),
            mulmod(_aa, mulmod(z, z, _pp), _pp),
            _pp
        );

        // x, y, z at this point will be reassigned and rather represent qx, qy, qz from the paper
        // This allows to reduce the gas cost and stack footprint of the algorithm
        // qx
        x = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
        // qy = -8*y1^4 + M(S-T)
        y = addmod(
            mulmod(m, addmod(s, _pp - x, _pp), _pp),
            _pp - mulmod(8, mulmod(y, y, _pp), _pp),
            _pp
        );
        // qz = 2*y1*z1
        z = mulmod(2, mulmod(_y, _z, _pp), _pp);

        return (x, y, z);
    }

    /// @dev Multiply point (x, y, z) times d.
    /// @param _d scalar to multiply
    /// @param _x coordinate x of P1
    /// @param _y coordinate y of P1
    /// @param _z coordinate z of P1
    /// @param _aa constant of curve
    /// @param _pp the modulus
    /// @return (qx, qy, qz) d*P1 in Jacobian
    function jacMul(
            uint256 _d,
            uint256 _x,
            uint256 _y,
            uint256 _z,
            uint256 _aa,
            uint256 _pp
        ) 
        internal pure 
        returns (uint256, uint256, uint256) 
    {
        // Early return in case that `_d == 0`
        if (_d == 0) {
            return (_x, _y, _z);
        }

        uint256 remaining = _d;
        uint256 qx = 0;
        uint256 qy = 0;
        uint256 qz = 1;

        // Double and add algorithm
        while (remaining != 0) {
            if ((remaining & 1) != 0) {
                (qx, qy, qz) = jacAdd(qx, qy, qz, _x, _y, _z, _pp);
            }
            remaining = remaining / 2;
            (_x, _y, _z) = jacDouble(_x, _y, _z, _aa, _pp);
        }
        return (qx, qy, qz);
    }
}

lib/openzeppelin-contracts/contracts/utils/Bytes.sol

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

pragma solidity ^0.8.24;

import {Math} from "./math/Math.sol";

/**
 * @dev Bytes operations.
 */
library Bytes {
    /**
     * @dev Forward search for `s` in `buffer`
     * * If `s` is present in the buffer, returns the index of the first instance
     * * If `s` is not present in the buffer, returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
     */
    function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
        return indexOf(buffer, s, 0);
    }

    /**
     * @dev Forward search for `s` in `buffer` starting at position `pos`
     * * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
     * * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
     */
    function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
        uint256 length = buffer.length;
        for (uint256 i = pos; i < length; ++i) {
            if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
                return i;
            }
        }
        return type(uint256).max;
    }

    /**
     * @dev Backward search for `s` in `buffer`
     * * If `s` is present in the buffer, returns the index of the last instance
     * * If `s` is not present in the buffer, returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
     */
    function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
        return lastIndexOf(buffer, s, type(uint256).max);
    }

    /**
     * @dev Backward search for `s` in `buffer` starting at position `pos`
     * * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
     * * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
     */
    function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
        unchecked {
            uint256 length = buffer.length;
            for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
                if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
                    return i - 1;
                }
            }
            return type(uint256).max;
        }
    }

    /**
     * @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
        return slice(buffer, start, buffer.length);
    }

    /**
     * @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
     * memory. The `end` argument is truncated to the length of the `buffer`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
        // sanitize
        end = Math.min(end, buffer.length);
        start = Math.min(start, end);

        // allocate and copy
        bytes memory result = new bytes(end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
        }

        return result;
    }

    /**
     * @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.
     *
     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
     */
    function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
        return splice(buffer, start, buffer.length);
    }

    /**
     * @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The
     * `end` argument is truncated to the length of the `buffer`.
     *
     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
     */
    function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
        // sanitize
        end = Math.min(end, buffer.length);
        start = Math.min(start, end);

        // allocate and copy
        assembly ("memory-safe") {
            mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
            mstore(buffer, sub(end, start))
        }

        return buffer;
    }

    /**
     * @dev Concatenate an array of bytes into a single bytes object.
     *
     * For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
     * `abi.encodePacked`.
     *
     * NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
     * significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
     */
    function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
        uint256 length = 0;
        for (uint256 i = 0; i < buffers.length; ++i) {
            length += buffers[i].length;
        }

        bytes memory result = new bytes(length);

        uint256 offset = 0x20;
        for (uint256 i = 0; i < buffers.length; ++i) {
            bytes memory input = buffers[i];
            assembly ("memory-safe") {
                mcopy(add(result, offset), add(input, 0x20), mload(input))
            }
            unchecked {
                offset += input.length;
            }
        }

        return result;
    }

    /**
     * @dev Returns true if the two byte buffers are equal.
     */
    function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
        return a.length == b.length && keccak256(a) == keccak256(b);
    }

    /**
     * @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
     * Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
     */
    function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
        value = // swap bytes
            ((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
            ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
        value = // swap 2-byte long pairs
            ((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
            ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
        value = // swap 4-byte long pairs
            ((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
            ((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
        value = // swap 8-byte long pairs
            ((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
            ((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
        return (value >> 128) | (value << 128); // swap 16-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 128-bit values.
    function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
        value = // swap bytes
            ((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
            ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
        value = // swap 2-byte long pairs
            ((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
            ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
        value = // swap 4-byte long pairs
            ((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
            ((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
        return (value >> 64) | (value << 64); // swap 8-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 64-bit values.
    function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
        value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
        value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
        return (value >> 32) | (value << 32); // swap 4-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 32-bit values.
    function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
        value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
        return (value >> 16) | (value << 16); // swap 2-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 16-bit values.
    function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
        return (value >> 8) | (value << 8);
    }

    /**
     * @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
     * if the buffer is all zeros.
     */
    function clz(bytes memory buffer) internal pure returns (uint256) {
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
            if (chunk != bytes32(0)) {
                return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
            }
        }
        return 8 * buffer.length;
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Strings.sol

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

pragma solidity ^0.8.24;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(add(buffer, 0x20), length)
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
     */
    function toHexString(bytes memory input) internal pure returns (string memory) {
        unchecked {
            bytes memory buffer = new bytes(2 * input.length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 0; i < input.length; ++i) {
                uint8 v = uint8(input[i]);
                buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
                buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
            }
            return string(buffer);
        }
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return Bytes.equal(bytes(a), bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i = 0; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     *
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Variant of {tryRecover} that takes a signature in calldata
     */
    function tryRecoverCalldata(
        bytes32 hash,
        bytes calldata signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, calldata slices would work here, but are
            // significantly more expensive (length check) than using calldataload in assembly.
            assembly ("memory-safe") {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Variant of {recover} that takes a signature in calldata
     */
    function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
     * formats. Returns (0,0,0) for invalid signatures.
     *
     * For 64-byte signatures, `v` is automatically normalized to 27 or 28.
     * For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
     *
     * Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
     */
    function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch mload(signature)
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := mload(add(signature, 0x40))
                r := mload(add(signature, 0x20))
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Variant of {parse} that takes a signature in calldata
     */
    function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch signature.length
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := calldataload(add(signature.offset, 0x20))
                r := calldataload(signature.offset)
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.24;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
     */
    function toDataWithIntendedValidatorHash(
        address validator,
        bytes32 messageHash
    ) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, hex"19_00")
            mstore(0x02, shl(96, validator))
            mstore(0x16, messageHash)
            digest := keccak256(0x00, 0x36)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

src/interfaces/IApplicationRegistry.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {BTCVaultTypes} from "../lib/BTCVaultTypes.sol";

/// @title IApplicationRegistry
/// @notice Interface for the ApplicationRegistry contract
/// @dev Manages application registration and vault keepers versioning
interface IApplicationRegistry {
    /// @notice Application status enum
    enum ApplicationStatus {
        None, // = 0 (default, unregistered)
        Active, // = 1 (application is active and can be used)
        Paused // = 2 (application is paused, all lifecycle operations are blocked)
    }

    /// @notice Structure representing a registered application
    struct ApplicationInfo {
        string name; // Application name
        address entryPoint; // application entry point smart contract address
        uint16 currentVaultKeepersVersion; // Active version of application-elected vault keepers
        ApplicationStatus status; // Application status
    }

    // ========== Events ==========

    /// @notice Emitted when an application is registered
    event ApplicationRegistered(address indexed applicationEntryPoint, string name);

    /// @notice Emitted when an application's status changes
    event ApplicationStatusChanged(
        address indexed appEntryPoint, ApplicationStatus oldStatus, ApplicationStatus newStatus
    );

    /// @notice Event emitted when application vault keepers are updated
    /// @param appEntryPoint The application entry point address
    /// @param appVaultKeepersVersion New application vault keepers version
    /// @param appVaultKeepers Full array of current application vault keepers
    event AppVaultKeepersUpdated(
        address indexed appEntryPoint, uint16 appVaultKeepersVersion, BTCVaultTypes.AddressBTCKeyPair[] appVaultKeepers
    );

    /// @notice Event emitted when a vault keeper blocklist status changes
    /// @param appEntryPoint The application entry point address
    /// @param vaultKeeper The vault keeper Ethereum address
    /// @param isBlocklisted Whether the vault keeper is now blocklisted
    event VaultKeeperBlocklistUpdated(address indexed appEntryPoint, address indexed vaultKeeper, bool isBlocklisted);

    /// @notice Emitted when a vault keeper appends a new operation BTC key version
    event OperationBtcKeyVersionAdded(
        address indexed appEntryPoint,
        address indexed keeperAdmin,
        uint16 indexed version,
        bytes32 opBtcKey,
        uint64 epoch
    );

    /// @notice Emitted when a vault keeper appends a new operation ETH key version
    event OperationEthKeyVersionAdded(
        address indexed appEntryPoint,
        address indexed keeperAdmin,
        uint16 indexed version,
        address opEthKey,
        uint64 epoch
    );

    /// @notice Emitted when a vault keeper appends a new payout script version
    event PayoutScriptVersionAdded(
        address indexed appEntryPoint,
        address indexed keeperAdmin,
        uint16 indexed version,
        bytes payoutScript,
        uint64 epoch
    );

    // ========== Application Management Functions ==========

    /// @notice Register a new application with initial vault keepers
    /// @param name The application name
    /// @param appEntryPoint The application entry point smart contract address
    /// @param appVaultKeepers The initial vault keepers for this application (version 1)
    /// @dev Can only be called by APP_ADMIN_ROLE
    /// @dev Application is registered with status Active and version 1
    function registerApplication(
        string memory name,
        address appEntryPoint,
        BTCVaultTypes.VaultKeeperRegistration[] memory appVaultKeepers
    ) external;

    /// @notice Pause an application
    /// @param appEntryPoint The application entry point address
    /// @dev Can only be called by APP_ADMIN_ROLE
    function pauseApplication(address appEntryPoint) external;

    /// @notice Activate a paused application
    /// @param appEntryPoint The application entry point address
    /// @dev Can only be called by APP_ADMIN_ROLE
    function activateApplication(address appEntryPoint) external;

    /// @notice Set a new version of vault keepers for an application
    /// @param appEntryPoint The application entry point address
    /// @param vaultKeepers Array of vault keepers for this version
    /// @dev Once a version is set, it cannot be modified (immutable)
    /// @dev This function increments by one the current vault keepers version for the application
    /// @dev Empty vault keepers lists are not allowed
    /// @dev Can only be called by APP_ADMIN_ROLE
    /// @dev A removed keeper may be re-listed with a PoP-verified operation-ETH replacement;
    ///      omitting it preserves the keeper's latest operation-ETH key
    function addVaultKeepersVersion(address appEntryPoint, BTCVaultTypes.VaultKeeperRegistration[] memory vaultKeepers)
        external;

    /// @notice Set blocklist status for a vault keeper address for an application
    /// @param appEntryPoint The application entry point address
    /// @param vaultKeeper The vault keeper Ethereum address
    /// @param isBlocklisted Whether the vault keeper should be blocklisted
    function setVaultKeeperBlocklist(address appEntryPoint, address vaultKeeper, bool isBlocklisted) external;

    // ========== View Functions ==========

    /// @notice Get the current status of an application
    /// @param appEntryPoint The application entry point address
    /// @return The application's current status
    function getApplicationStatus(address appEntryPoint) external view returns (ApplicationStatus);

    /// @notice Get application info
    /// @param appEntryPoint The application entry point address
    /// @return info The ApplicationInfo struct
    function getApplicationInfo(address appEntryPoint) external view returns (ApplicationInfo memory info);

    /// @notice Get vault keepers for a specific roster version
    /// @param appEntryPoint The application entry point address
    /// @param versionNumber The version number
    /// @return Array of vault keepers for the specified version
    /// @dev The version axis is roster membership, not key rotation; each pair's `btcPubKey` is
    ///      the keeper's genesis roster key. Resolve keys per keeper via
    ///      `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `appKeeperKeyEpochCurrent`).
    function getVaultKeepersByVersion(address appEntryPoint, uint16 versionNumber)
        external
        view
        returns (BTCVaultTypes.AddressBTCKeyPair[] memory);

    /// @notice Get the current active vault keepers for an application
    /// @param appEntryPoint The application entry point address
    /// @return Array of current vault keepers
    /// @dev Current in roster membership only; each pair's `btcPubKey` is the keeper's genesis
    ///      roster key. Resolve keys per keeper via
    ///      `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `appKeeperKeyEpochCurrent`).
    function getCurrentVaultKeepers(address appEntryPoint)
        external
        view
        returns (BTCVaultTypes.AddressBTCKeyPair[] memory);

    /// @notice Get the current vault keepers version for an application
    /// @param appEntryPoint The application entry point address
    /// @return The current version number
    function getCurrentVaultKeepersVersion(address appEntryPoint) external view returns (uint16);

    /// @notice Check if an address is a registered vault keeper for an application (current version)
    /// @param appEntryPoint The application entry point address
    /// @param account The address to check
    /// @return True if the account is a registered vault keeper
    function isVaultKeeper(address appEntryPoint, address account) external view returns (bool);

    /// @notice Check if an address is a registered vault keeper for a specific version
    /// @param appEntryPoint The application entry point address
    /// @param account The address to check
    /// @param version The version number to check against
    /// @return True if the account is a registered vault keeper
    function isVaultKeeperInVersion(address appEntryPoint, address account, uint16 version) external view returns (bool);

    /// @notice Get the BTC public key for a specific vault keeper
    /// @param appEntryPoint The application entry point address
    /// @param vaultKeeper The vault keeper's Ethereum address
    /// @return The BTC public key registered for this vault keeper
    function getVaultKeeperBTCKey(address appEntryPoint, address vaultKeeper) external view returns (bytes32);

    /// @notice Get the BTC public key for a specific vault keeper in a specific version
    /// @param appEntryPoint The application entry point address
    /// @param vaultKeeper The vault keeper's Ethereum address
    /// @param version The version number to check against
    /// @return The BTC public key registered for this vault keeper
    function getVaultKeeperBTCKeyInVersion(address appEntryPoint, address vaultKeeper, uint16 version)
        external
        view
        returns (bytes32);

    /// @notice Get the vault keeper Ethereum address for a BTC public key
    /// @param appEntryPoint The application entry point address
    /// @param btcPubKey The vault keeper BTC public key
    /// @return The vault keeper Ethereum address bound to this BTC key
    function getVaultKeeperEthAddressByBtcKey(address appEntryPoint, bytes32 btcPubKey) external view returns (address);

    /// @notice Check if a BTC public key is a registered vault keeper in a specific version
    /// @param appEntryPoint The application entry point address
    /// @param btcPubKey The BTC public key to check
    /// @param version The version number to check against
    /// @return True if the BTC public key is registered as a vault keeper
    function isVaultKeeperByBtcKeyInVersion(address appEntryPoint, bytes32 btcPubKey, uint16 version)
        external
        view
        returns (bool);

    /// @notice Check if a vault keeper address is blocklisted for an application
    /// @param appEntryPoint The application entry point address
    /// @param account The vault keeper Ethereum address
    /// @return True if the vault keeper is blocklisted
    function isBlocklistedVaultKeeper(address appEntryPoint, address account) external view returns (bool);

    /// @notice Validate that a vault keeper BTC key can redeem for an application at a bonded version+epoch
    /// @param appEntryPoint The application entry point address
    /// @param btcPubKey The vault keeper BTC public key
    /// @param appVaultKeepersVersion The vault's frozen keeper membership version
    /// @param appKeeperKeyEpoch The vault's frozen keeper operation-key epoch
    /// @dev Confirms the keeper is a member of the frozen membership version and that the supplied key
    ///      is the keeper's op-key bonded at `appKeeperKeyEpoch` (genesis = the frozen-version roster key).
    /// @dev Reverts with `UnauthorizedVaultKeeper` or `BlocklistedVaultKeeper`
    function assertVaultKeeperCanRedeem(
        address appEntryPoint,
        bytes32 btcPubKey,
        uint16 appVaultKeepersVersion,
        uint64 appKeeperKeyEpoch
    ) external view;

    // ========== Operation Key / Payout Versioning ==========

    /// @notice Current per-app keeper operation-key epoch
    function appKeeperKeyEpochCurrent(address appEntryPoint) external view returns (uint64);

    /// @notice Append a new keeper operation BTC key version (admin-gated, new-key self-PoP)
    function setOperationBtcKey(address appEntryPoint, bytes32 newOpBtcKey, bytes calldata btcPopSignature) external;

    /// @notice Append a new keeper operation ETH (relay/ACK) key version (admin-gated, new-key self-PoP)
    function setOperationEthKey(address appEntryPoint, address newOpEthKey, bytes calldata ethPopSignature) external;

    /// @notice Append a new keeper payout script version (admin-gated, no PoP)
    function setPayoutScript(address appEntryPoint, bytes calldata newPayoutScript) external;

    /// @notice Latest keeper operation BTC key version (0 = genesis roster key)
    function latestOperationBtcKeyVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);

    /// @notice Keeper operation BTC key at a specific version (v0 = genesis roster key)
    function getOperationBtcKeyByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
        external
        view
        returns (bytes32);

    /// @notice Current (latest) keeper operation BTC key
    function getCurrentOperationBtcKey(address appEntryPoint, address keeperAdmin) external view returns (bytes32);

    /// @notice Latest keeper operation ETH key version (0 = admin default)
    function latestOperationEthKeyVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);

    /// @notice Keeper operation ETH key at a specific version (v0 = keeperAdmin)
    function getOperationEthKeyByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
        external
        view
        returns (address);

    /// @notice Current (latest) keeper operation ETH key
    function getCurrentOperationEthKey(address appEntryPoint, address keeperAdmin) external view returns (address);

    /// @notice Latest keeper payout script version (0 = legacy/default BIP-86)
    function latestPayoutScriptVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);

    /// @notice Keeper payout script at a specific version (v0 = BIP-86 of op-key v0)
    function getPayoutScriptByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
        external
        view
        returns (bytes memory);

    /// @notice Current (latest) keeper payout script (BIP-86 default when none set)
    function getCurrentPayoutScript(address appEntryPoint, address keeperAdmin) external view returns (bytes memory);

    /// @notice Keeper operation BTC key bonded to a vault's epoch (v0 = genesis roster key)
    function getOperationBtcKeyAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
        external
        view
        returns (bytes32);

    /// @notice Keeper operation BTC key bonded to a vault's epoch against an explicit roster-version
    ///         genesis: latest op-key version whose epoch <= bonded epoch, else `rosterGenesisKey`
    /// @dev The caller supplies the keeper's key from the vault's FROZEN membership version as the v0
    ///      genesis. Correct even if the keeper rotated across versions or was later dropped from the roster.
    function getOperationBtcKeyAtEpochOrGenesis(
        address appEntryPoint,
        address keeperAdmin,
        uint64 epoch,
        bytes32 rosterGenesisKey
    ) external view returns (bytes32);

    /// @notice Keeper operation ETH key bonded to a vault's epoch (v0 = keeperAdmin)
    function getOperationEthKeyAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
        external
        view
        returns (address);

    /// @notice Keeper payout script bonded to a vault's epoch (v0 = BIP-86 of op-key v0)
    function getPayoutScriptAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
        external
        view
        returns (bytes memory);
}

src/lib/BTCVaultTypes.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

/// @title BTCVaultTypes
/// @notice Shared BTC vault types used across protocol and application boundaries
library BTCVaultTypes {
    /// @notice Struct pairing an Ethereum address with its corresponding BTC public key
    struct AddressBTCKeyPair {
        address ethAddress;
        bytes32 btcPubKey;
    }

    /// @notice Vault keeper roster-registration input: identity + genesis op-key + required payout
    /// @dev adminEthAddress is the immutable authority + history key; opBtcKey is op-key v0;
    ///      payoutScript is recorded as payout v1 (v0 is the BIP-86 default, derived on read).
    ///      opEthKey optionally bootstraps a distinct operation-ETH key at first listing or appends
    ///      a replacement when re-listing a removed keeper (address(0) retains the current key).
    ///      ethPopSignature is the EIP-191 self-PoP by opEthKey, required when opEthKey is set and
    ///      ignored otherwise.
    struct VaultKeeperRegistration {
        address adminEthAddress;
        bytes32 opBtcKey;
        bytes payoutScript;
        address opEthKey;
        bytes ethPopSignature;
    }

    /// @notice Pegin request status enum
    enum BTCVaultStatus {
        Pending, // Request submitted, waiting for ACKs
        Verified, // All ACKs collected, ready for secret activation
        Active, // Secret revealed, vault is active and usable
        Redeemed, // Vault has been redeemed, BTC is claimable
        Expired // Pegin request expired (timeout exceeded before activation)
    }

    /// @notice Vault fields needed for lightweight reads and activation callbacks
    struct BTCVaultBasicInfo {
        address depositor; // Original vault creator
        bytes32 depositorBtcPubKey; // Depositor's x-only BTC public key
        uint256 amount; // Vault amount in satoshis
        address vaultProvider; // Vault provider assigned to this vault
        BTCVaultStatus status; // Current vault lifecycle state
        address applicationEntryPoint; // Application that owns the vault
        uint256 createdAt; // Ethereum block number when the vault was created
    }
}

src/protocol/interfaces/IFeeEscrow.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title IFeeEscrow
 * @notice Interface for the FeeEscrow contract
 * @dev Manages protocol-level fees with escrow and pull-based claiming
 */
interface IFeeEscrow {
    // ═══════════════════════════════════════════════════════════════════════════
    //                                  EVENTS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Emitted when pegin fees are escrowed at submission time
    event PegInFeesEscrowed(
        bytes32 indexed vaultId,
        uint256 totalAmount,
        address vaultProvider,
        uint256 numUniversalChallengers,
        uint256 numAppVaultKeepers
    );

    /// @notice Emitted when escrowed fees are distributed to claimable balances
    event PegInFeesDistributed(
        bytes32 indexed vaultId,
        address indexed vaultProvider,
        uint256 numUniversalChallengers,
        uint256 numAppVaultKeepers
    );

    /// @notice Emitted when escrowed fees are forfeited to the protocol
    ///         treasury on ACK-timeout expiry. `depositor` is indexed so the
    ///         treasury operator can attribute manual, off-chain refunds for
    ///         not-at-fault depositors from logs.
    event PegInFeesForfeited(bytes32 indexed vaultId, address indexed depositor, uint256 amount);

    /// @notice Emitted when fees are claimed
    event FeesClaimed(address indexed claimer, uint256 amount);

    /// @notice Emitted when a vault provider registration fee is escrowed
    event RegistrationFeeEscrowed(address indexed recipient, uint256 amount);

    /// @notice Emitted when fee rates are updated
    event FeesUpdated(
        uint128 vpFeeRate,
        uint128 ucFeeRate,
        uint128 avkFeeRate,
        uint128 protocolPegInFeeRate,
        uint128 vpRegistrationFee
    );

    // ═══════════════════════════════════════════════════════════════════════════
    //                                  STRUCTS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Escrowed pegin fee details
    struct EscrowedPeginFees {
        uint128 vpFee; // Fixed fee for vault provider
        uint128 ucFeePerKeeper; // Fixed fee per universal challenger
        uint128 avkFeePerKeeper; // Fixed fee per app vault keeper
        uint128 protocolFee; // Fixed protocol fee
        uint256 totalFee; // Total escrowed fee amount
        uint16 numUniversalChallengers; // Number of UCs at escrow time
        uint16 numAppVaultKeepers; // Number of AVKs at escrow time
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                              CORE FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * @notice Escrow pegin fees at vault submission time
     * @param vaultId The vault identifier
     * @param vaultProvider Address of the vault provider
     * @param numUniversalChallengers Number of universal challengers
     * @param numAppVaultKeepers Number of app vault keepers
     * @dev Only callable by BTCVaultRegistry
     * @dev Must receive exact required fee amount via msg.value
     */
    function escrow(bytes32 vaultId, address vaultProvider, uint256 numUniversalChallengers, uint256 numAppVaultKeepers)
        external
        payable;

    /**
     * @notice Distribute escrowed fees to claimable balances after ACK completion
     * @param vaultId The vault identifier
     * @param vaultProvider Address of the vault provider
     * @param universalChallengers Array of universal challenger addresses
     * @param appVaultKeepers Array of app vault keeper addresses
     * @dev Only callable by BTCVaultRegistry
     */
    function distribute(
        bytes32 vaultId,
        address vaultProvider,
        address[] calldata universalChallengers,
        address[] calldata appVaultKeepers
    ) external;

    /**
     * @notice Forfeit escrowed fees to the protocol treasury when a Pending
     *         vault expires (ACK timeout)
     * @param vaultId The vault identifier
     * @param depositor The depositor whose fee is forfeited (event attribution
     *        for manual off-chain reimbursement)
     * @dev Only callable by BTCVaultRegistry
     * @dev Credits the full fee to the protocol treasury's claimable balance
     *      (pull-based, drawn via `claim`), so expiry reporting never depends
     *      on the treasury's ability to receive ETH
     */
    function forfeit(bytes32 vaultId, address depositor) external;

    /**
     * @notice Claim accumulated fees for caller
     * @dev Reverts if caller has no claimable balance
     */
    function claim() external;

    // ═══════════════════════════════════════════════════════════════════════════
    //                              ADMIN FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * @notice Update fee rates
     * @param _vpFeeRate New VP fee rate (wei)
     * @param _ucFeeRate New UC fee rate per keeper (wei)
     * @param _avkFeeRate New AVK fee rate per keeper (wei)
     * @param _protocolPegInFeeRate New protocol fee rate (wei)
     * @param _vpRegistrationFee New VP registration fee (wei)
     * @dev Only callable by admin
     */
    function updateFees(
        uint128 _vpFeeRate,
        uint128 _ucFeeRate,
        uint128 _avkFeeRate,
        uint128 _protocolPegInFeeRate,
        uint128 _vpRegistrationFee
    ) external;

    // ═══════════════════════════════════════════════════════════════════════════
    //                              VIEW FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * @notice Get claimable balance for an address
     * @param account The address to check
     * @return amount The claimable amount in wei
     */
    function claimable(address account) external view returns (uint256 amount);

    /**
     * @notice Get escrowed fees for a vault
     * @param vaultId The vault identifier
     * @return fees The escrowed fee information
     */
    function getEscrowedFees(bytes32 vaultId) external view returns (EscrowedPeginFees memory fees);

    /**
     * @notice Calculate required pegin fee for given keeper counts
     * @param numUniversalChallengers Number of universal challengers
     * @param numAppVaultKeepers Number of app vault keepers
     * @return totalFee The total required fee in wei
     */
    function getRequiredFee(uint256 numUniversalChallengers, uint256 numAppVaultKeepers)
        external
        view
        returns (uint256 totalFee);

    /**
     * @notice Get all pegin fee rates
     * @return vpFee VP fee rate (wei)
     * @return ucFee UC fee rate per keeper (wei)
     * @return avkFee AVK fee rate per keeper (wei)
     * @return protocolFee Protocol fee rate (wei)
     */
    function getPegInFeeRates()
        external
        view
        returns (uint128 vpFee, uint128 ucFee, uint128 avkFee, uint128 protocolFee);

    /**
     * @notice Get VP registration fee
     * @return fee VP registration fee amount (wei)
     */
    function vpRegistrationFee() external view returns (uint128 fee);

    /**
     * @notice Get protocol treasury address
     * @return treasury Protocol treasury address
     */
    function protocolTreasury() external view returns (address treasury);
}

src/protocol/interfaces/IProtocolParams.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {BTCVaultTypes} from "../../lib/BTCVaultTypes.sol";

/// @title IProtocolParams
/// @notice Interface for the ProtocolParams contract
interface IProtocolParams {
    struct TBVProtocolParams {
        // ------------- PegIn Configuration -------------
        /// @notice Minimum amount that depositor must lock into the vault (in satoshis)
        /// @dev Anti-spam mechanism to prevent system abuse
        uint64 minimumPegInAmount;
        /// @notice Maximum amount that depositor can lock into the vault (in satoshis)
        uint64 maxPegInAmount;
        /// @notice Timeout for all required ACKs to be submitted (in ETH blocks)
        /// @dev Short window (e.g. ~1 day). If ACKs are not collected within this window, the vault can be expired.
        uint64 pegInAckTimeout;
        /// @notice Timeout for pegin activation after vault creation (in ETH blocks)
        /// @dev Window from createdAt within which activateVaultWithSecret must be called
        uint64 pegInActivationTimeout;
        /// @notice Maximum number of HTLC outputs allowed in a batched Pre-PegIn transaction
        /// @dev Prevents Pre-PegIns with too many outputs that can't all be processed before tStale expiry
        uint8 maxHtlcOutputCount;
        /// @notice Grace window after the activation deadline during which `claimExpiredVault` may be called (in ETH blocks)
        /// @dev Cutoff is `block.number > (block.number at reportExpired) + expiredPegInGraceBlocks`. Must align with vaultd's
        ///      deferred artifact retention window so on-chain claims remain actionable off-chain.
        uint64 expiredPegInGraceBlocks;
        /// @notice Observation window enforced between ACK completion and application activation (in ETH blocks)
        /// @dev Measured from `verifiedAt`, the block at which the final required ACK moved the vault to `Verified`.
        ///      A complete ACK set asserts the Pre-PegIn is confirmed to `minPrepeginDepth` on Bitcoin, so an ACKed
        ///      vault with no corresponding Bitcoin transaction is an observable protocol violation. This window
        ///      denies colluding participants the ability to ACK and activate atomically, giving monitoring time to
        ///      pause the application before vaultBTC is minted as Aave collateral. Only `activateVaultWithSecret`
        ///      is gated; `activateVaultWithSecretAndRedeem` mints nothing and stays available as an unwind path.
        ///      Set to 0 to disable.
        uint64 peginActivationDelay;
        /// @notice Maximum number of funding inputs allowed in a Pre-PegIn or Claim transaction
        /// @dev Enforced on-chain against `unsignedPrePeginTx` at peg-in submission. Off-chain actors read the
        ///      same bound to size Claim transactions, which never reach this contract. Bounding the input side
        ///      denies a depositor the ability to fan one Ethereum submission out into an unbounded per-input
        ///      `getrawtransaction` storm across every VP, VK and UC ingesting the resulting `PegInSubmitted`
        ///      event. Appended after `peginActivationDelay` so it extends the existing packed slot rather
        ///      than shifting the offsets of the fields above it.
        uint8 maxFundingInputCount;
    }

    /// @notice Versioned offchain parameters for off-chain actors
    /// @dev These parameters are used by off-chain actors for data availability and protocol operation
    struct VersionedOffchainParams {
        // Bitcoin timing parameters (in BTC blocks)
        uint256 timelockAssert; // Timelock for assert period (blocks)
        uint256 timelockChallengeAssert; // Timelock for challenge-assert period (blocks)
        bytes32[] securityCouncilKeys; // Array of BTC public keys for security council members
        uint8 councilQuorum; // Number of signatures required for council action (n-of-m multisig)
        // TX Graph Construction Parameters
        uint64 feeRate; // Fee rate in sat/vB (e.g., 2 = 2 sat/vB)
        // BaBe Cut-and-Choose Protocol Parameters
        uint16 babeTotalInstances; // Total number of GC instances created in cut-and-choose protocol
        uint8 babeInstancesToFinalize; // Number of GC instances to finalize (closed instances used for evaluation)
        // Maximum vault provider commission in basis points (10000 = 100%, 1 = 0.01%).
        // Must be >= Constants.MIN_VP_COMMISSION_BPS (1) and < 10000
        // Individual VPs set their own commission in [MIN_VP_COMMISSION_BPS, this cap] during registration and
        // commission updates
        uint16 maxVpCommissionBps;
        // ------------- Atomic Swap Timing Parameters (in BTC blocks) -------------
        /// @notice Refund timelock for atomic swap pre-pegin transaction (in BTC blocks)
        /// @dev After this many BTC blocks, the depositor can reclaim funds if the swap was not completed
        uint32 tRefund;
        /// @notice Staleness threshold for pre-pegin transactions (in BTC blocks)
        /// @dev Pre-pegin transactions older than this are considered stale and should be rejected by off-chain actors
        uint32 tStale;
        /// @notice Minimum fee rate for pegin transactions (in sat/vB)
        /// @dev Off-chain actors validate that the pegin tx meets this minimum fee rate before ACKing
        uint64 minPeginFeeRate;
        // ------------- Prover Circuit Version -------------
        /// @notice Prover circuit version matching the prover CircuitVersion enum
        /// @dev Identifies which prover circuit (universal SP1 ELF set) to use for this parameter set
        uint16 proverCircuitVersion;
        /// @notice Minimum number of BTC confirmations required for a Pre-PegIn transaction before ACK signing
        /// @dev Off-chain actors (VP, VK, UC) must wait for this many confirmations before signing ACKs
        uint32 minPrepeginDepth;
    }

    // ========== Events ==========

    /// @notice Emitted once when a circuit version's verifier and checkpoint are approved
    /// @param circuitVersion The nonzero on-chain circuit version
    /// @param pegoutCircuitVkHash Outer peg-out SP1 VK hash in bytes32() form
    /// @param trustedCheckpoint Approved bootstrap beacon block root
    event ProverInfoRegistered(uint16 indexed circuitVersion, bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint);

    /// @notice Emitted when a new version of offchain parameters is added
    /// @param version The version number
    /// @param params The offchain parameters for this version
    event OffchainParamsVersionAdded(uint16 indexed version, VersionedOffchainParams params);

    /// @notice Emitted when a new version of universal challengers is added
    /// @param version The version number
    /// @param challengers Array of universal challengers for this version
    event UniversalChallengersVersionAdded(uint256 indexed version, BTCVaultTypes.AddressBTCKeyPair[] challengers);

    /// @notice Emitted when protocol parameters are updated
    /// @param params The updated protocol parameters
    event ProtocolParamsUpdated(IProtocolParams.TBVProtocolParams params);

    /// @notice Emitted when the active vault Core version changes
    /// @param previousVersion The previously active Core version (0 at initialization)
    /// @param newVersion The newly active Core version
    event ActiveVaultCoreVersionUpdated(uint16 indexed previousVersion, uint16 indexed newVersion);

    /// @notice Emitted when a UC appends an operation-BTC-key version
    event OperationBtcKeyVersionAdded(address indexed ucAdmin, uint16 indexed version, bytes32 opBtcKey, uint64 epoch);

    /// @notice Emitted when a UC appends an operation-ETH-key version
    event OperationEthKeyVersionAdded(address indexed ucAdmin, uint16 indexed version, address opEthKey, uint64 epoch);

    // ========== Universal Challengers Functions ==========

    /// @notice Add a new version of universal challengers
    /// @param challengers Array of universal challenger roster registrations for this version
    /// @dev Auto-increments the version number
    function addUniversalChallengersVersion(BTCVaultTypes.AddressBTCKeyPair[] calldata challengers) external;

    /// @notice Get the latest universal challengers version number
    /// @return The latest version number
    function latestUniversalChallengersVersion() external view returns (uint16);

    /// @notice Get universal challengers for a specific roster version
    /// @param versionNumber The version number
    /// @return Array of universal challengers for the specified version
    /// @dev The version axis is roster membership, not key rotation; each pair's `btcPubKey` is
    ///      the member's genesis roster key. Resolve keys per member via
    ///      `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `ucKeyEpochCurrent`).
    function getUniversalChallengersByVersion(uint16 versionNumber)
        external
        view
        returns (BTCVaultTypes.AddressBTCKeyPair[] memory);

    /// @notice Get the current active universal challengers
    /// @return Array of current universal challengers
    /// @dev Current in roster membership only; each pair's `btcPubKey` is the member's genesis
    ///      roster key. Resolve keys per member via
    ///      `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `ucKeyEpochCurrent`).
    function getCurrentUniversalChallengers() external view returns (BTCVaultTypes.AddressBTCKeyPair[] memory);

    // ========== UC Operation Key Functions ==========

    /// @notice Global UC operation-key epoch counter
    function ucKeyEpochCurrent() external view returns (uint64);

    /// @notice Latest UC operation-BTC-key version (0 = genesis)
    function latestOperationBtcKeyVersion(address ucAdmin) external view returns (uint16);

    /// @notice UC operation-BTC-key by version (v0 = genesis op key)
    function getOperationBtcKeyByVersion(address ucAdmin, uint16 version) external view returns (bytes32);

    /// @notice Current UC operation-BTC-key (latest version, or genesis when unrotated)
    function getCurrentOperationBtcKey(address ucAdmin) external view returns (bytes32);

    /// @notice Latest UC operation-ETH-key version (0 = admin default)
    function latestOperationEthKeyVersion(address ucAdmin) external view returns (uint16);

    /// @notice UC operation-ETH-key by version (v0 = ucAdmin)
    function getOperationEthKeyByVersion(address ucAdmin, uint16 version) external view returns (address);

    /// @notice Current UC operation-ETH-key (latest version, or admin when unrotated)
    function getCurrentOperationEthKey(address ucAdmin) external view returns (address);

    /// @notice Append a new UC operation BTC key version (admin-gated, new-key self-PoP)
    function setOperationBtcKey(bytes32 newOpBtcKey, bytes calldata btcPopSignature) external;

    /// @notice Append a new UC operation ETH (relay/ACK) key version (admin-gated, new-key self-PoP)
    function setOperationEthKey(address newOpEthKey, bytes calldata ethPopSignature) external;

    /// @notice UC op-BTC key bonded to a vault's ucKeyEpoch (v0 = genesis op key)
    function getOperationBtcKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (bytes32);

    /// @notice UC op-BTC key bonded to a vault's ucKeyEpoch against an explicit roster-version genesis:
    ///         latest op-key version whose epoch <= bonded epoch, else `rosterGenesisKey`
    /// @dev The caller supplies the UC's key from the vault's FROZEN membership version as the v0
    ///      genesis. Correct even if the UC rotated across versions or was later dropped from the roster.
    function getOperationBtcKeyAtEpochOrGenesis(address ucAdmin, uint64 epoch, bytes32 rosterGenesisKey)
        external
        view
        returns (bytes32);

    /// @notice UC op-ETH key bonded to a vault's ucKeyEpoch (v0 = ucAdmin)
    function getOperationEthKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (address);

    // ========== Prover Info ==========

    /// @notice Register the approved verifier and checkpoint for a circuit version
    /// @dev Admin-only, set-once. Required for offchain parameter updates, but does not gate PegIns.
    /// @param circuitVersion Nonzero on-chain circuit version; must not already be registered
    /// @param pegoutCircuitVkHash Nonzero approved outer peg-out SP1 VK hash; no cryptographic validation
    /// @param trustedCheckpoint Nonzero bootstrap beacon block root; zero is reserved for unregistered versions
    function registerProverInfo(uint16 circuitVersion, bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint) external;

    /// @notice Get the approved verifier inputs; unregistered versions return zeros
    /// @param circuitVersion Version from the vault's frozen offchain parameters, not the latest params
    /// @return pegoutCircuitVkHash Outer peg-out SP1 VK hash in bytes32() form
    /// @return trustedCheckpoint Approved bootstrap beacon block root, or zero if unregistered
    function getProverInfo(uint16 circuitVersion)
        external
        view
        returns (bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint);

    // ========== Offchain Parameters Functions ==========

    /// @notice Add a new version of offchain parameters
    /// @dev Requires registered prover info for proverCircuitVersion, whether higher, equal, or lower.
    /// @dev Auto-increments the version number; each parameter set is immutable.
    /// @param params The offchain parameters for this version
    function addOffchainParamsVersion(VersionedOffchainParams calldata params) external;

    /// @notice Get the latest offchain parameters version number
    /// @return The latest version number
    function latestOffchainParamsVersion() external view returns (uint16);

    /// @notice Get offchain parameters for a specific version
    /// @param versionNumber The version number
    /// @return The offchain parameters for the specified version
    function getOffchainParamsByVersion(uint16 versionNumber) external view returns (VersionedOffchainParams memory);

    /// @notice Get the latest offchain parameters
    /// @return The latest offchain parameters
    function getLatestOffchainParams() external view returns (VersionedOffchainParams memory);

    // ========== Vault Core Version Functions ==========

    /// @notice Get the currently active vault Core version (RFC 004)
    /// @dev Stamped onto every new vault at peg-in submission
    /// @return The active vault Core version
    function activeVaultCoreVersion() external view returns (uint16);

    /// @notice Set the active vault Core version (admin-only)
    /// @dev Accepts upgrades and rollbacks; rejects 0 and the current version
    /// @param newVersion The new active vault Core version
    function setActiveVaultCoreVersion(uint16 newVersion) external;

    // ========== Upgrade Functions ==========

    /// @notice Get the contract version
    /// @return Version string
    function version() external pure returns (string memory);

    function minimumPegInAmount() external view returns (uint256);

    function maxPegInAmount() external view returns (uint256);

    function pegInAckTimeout() external view returns (uint256);

    function pegInActivationTimeout() external view returns (uint256);

    function expiredPegInGraceBlocks() external view returns (uint256);

    function peginActivationDelay() external view returns (uint256);

    function getTBVProtocolParams() external view returns (TBVProtocolParams memory);
}

src/protocol/lib/BTCProofOfPossession.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import "./helpers/Secp256k1.sol";
import "./helpers/BIP340Utils.sol";
import "./helpers/BIP322Utils.sol";

/**
 * @title BTCProofOfPossession
 * @notice Library for verifying Bitcoin BIP-322 proof of possession signatures
 * @dev Verifies that a BTC private key signed a message containing an Ethereum
 *      address hex representation to prove ownership
 * @dev BIP-322 verification supports P2WPKH (using ECDSA) and P2TR key-path
 *      (using Schnorr) address types
 * @dev This library is deployed as an EXTERNAL library to reduce contract size
 */
library BTCProofOfPossession {
    // ========== CONSTANTS ==========

    /// @notice Action constants for PoP signature context
    bytes32 internal constant ACTION_REGISTER = keccak256("register");

    /// @notice Action constant for declaring/rotating an operation BTC key
    bytes32 internal constant ACTION_SET_OPERATION_BTC_KEY = keccak256("set_operation_btc_key");

    /// @notice Minimum valid BIP-322 PoP signature length (P2TR with
    ///         SIGHASH_DEFAULT: 1 count + 1 length + 64 sig)
    uint256 internal constant MIN_POP_SIGNATURE_LENGTH = 66;

    /// @notice Maximum valid BIP-322 PoP signature length (P2WPKH: 1 count +
    ///         1 sigLen + 73 DER+sighash + 1 pkLen + 33 pk)
    uint256 internal constant MAX_POP_SIGNATURE_LENGTH = 109;

    // ========== ERRORS ==========

    /// @notice Error for invalid BTC PoP signature length
    error InvalidBTCPopSignatureLength(uint256 length, uint256 minLength, uint256 maxLength);

    /// @notice Error for invalid action string
    error InvalidAction(bytes32 action);

    /// @notice Error for public key mismatch
    error PublicKeyMismatch(bytes32 expected, bytes32 actual);

    /// @notice Error for invalid S value (not normalized)
    error InvalidSValue(bytes32 s);

    /// @notice Error for unsupported address type
    error UnsupportedAddressType(uint8 witnessItemCount);

    /// @notice Error for invalid BIP-322 signature
    error InvalidBIP322Signature(uint256 offset, uint256 length);

    /// @notice Error for invalid witness data
    error InvalidWitnessData(uint256 offset, uint256 expected, uint256 actual);

    // ========== EXTERNAL FUNCTIONS ==========

    /**
     * @notice Verify a BIP-322 proof of possession
     * @dev Verifies that the BTC private key corresponding to bip340PubKeyX
     *      signed the owner address
     * @dev Includes chain ID, action, and verifying contract address to prevent
     *      cross-chain, cross-context, and cross-contract replay attacks
     * @dev Message format:
     *      "0x<address>:<chainId>:<action>:<verifying_contract>"
     * @dev Both address and verifying_contract are lowercase hex strings
     * @dev BIP-322 signatures are witness-encoded and must be between 66 and
     *      109 bytes
     * @param signature The BIP-322 witness-encoded signature
     * @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
     *        against
     * @param owner The Ethereum address that was in the signed message
     * @param action The action context for the signature
     * @return True if the signature is valid
     */
    function verify(bytes memory signature, bytes32 bip340PubKeyX, address owner, bytes32 action)
        external
        view
        returns (bool)
    {
        if (action != ACTION_REGISTER) {
            revert InvalidAction(action);
        }

        bytes memory message = buildMessage(owner, block.chainid, action, address(this));

        if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
            revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
        }

        return verify(signature, bip340PubKeyX, message);
    }

    /**
     * @notice Verify a BIP-322 proof of possession bound to an extra payload
     * @dev Message format:
     *      "0x<address>:<chainId>:<action>:<verifying_contract>:<payload_hex>"
     *      Lowercase hex for address, verifying_contract and payload.
     * @dev The payload is included in the signed message, so an attacker
     *      cannot replay a signature with a different payload.
     * @param signature The BIP-322 witness-encoded signature
     * @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
     *        against
     * @param owner The Ethereum address that was in the signed message
     * @param action The action context (ACTION_SET_OPERATION_BTC_KEY)
     * @param payload Arbitrary payload bytes bound into the signed message
     * @return True if the signature is valid
     */
    function verifyWithPayload(
        bytes memory signature,
        bytes32 bip340PubKeyX,
        address owner,
        bytes32 action,
        bytes memory payload
    ) external view returns (bool) {
        if (action != ACTION_SET_OPERATION_BTC_KEY) {
            revert InvalidAction(action);
        }

        bytes memory message = buildMessageWithPayload(owner, block.chainid, action, address(this), payload);

        if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
            revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
        }

        return verify(signature, bip340PubKeyX, message);
    }

    // ========== INTERNAL FUNCTIONS ==========

    /**
     * @notice Verify BIP-322 proof of possession signature
     * @dev Detects address type from witness structure
     *      - P2TR key-path: 1 witness item (Schnorr signature)
     *      - P2WPKH: 2 witness items (ECDSA signature + compressed public key)
     * @param signature The BIP-322 simple signature bytes (witness data)
     * @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
     *        against
     * @param message The message that was signed
     * @return True if the signature is valid and matches the public key
     */
    function verify(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message) internal pure returns (bool) {
        if (signature.length == 0 || message.length == 0) {
            revert InvalidBIP322Signature(signature.length, message.length);
        }

        if (signature.length < 2) {
            revert InvalidWitnessData(0, 2, signature.length);
        }

        uint8 witnessItemCount = uint8(signature[0]);

        if (witnessItemCount == 1) {
            return verifyBIP322P2TR(signature, bip340PubKeyX, message);
        }

        if (witnessItemCount == 2) {
            return verifyBIP322P2WPKH(signature, bip340PubKeyX, message);
        }

        revert UnsupportedAddressType(witnessItemCount);
    }

    /**
     * @notice Verify BIP-322 signature for P2TR (Taproot) address with key-path spending
     * @dev Uses BIP-340 Schnorr signature verification with tweaked output key
     * @dev Accepts both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
     * @param signature The witness data containing the Schnorr signature
     * @param bip340PubKeyX The x-only internal public key
     * @param message The message that was signed
     * @return True if verification succeeds
     */
    function verifyBIP322P2TR(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
        internal
        pure
        returns (bool)
    {
        uint8 witnessItemCount = uint8(signature[0]);
        if (witnessItemCount != 1) {
            revert InvalidWitnessData(0, 1, witnessItemCount);
        }

        uint8 sigLength = uint8(signature[1]);
        if (sigLength != 64 && sigLength != 65) {
            revert InvalidWitnessData(1, 64, sigLength);
        }

        // Canonical BIP-322 P2TR witness is exactly 2 + sigLength bytes
        // (1 witnessItemCount + 1 sigLength + sigLength). Trailing bytes
        // are rejected to prevent proof malleability.
        if (signature.length != 2 + uint256(sigLength)) {
            revert InvalidWitnessData(0, 2 + uint256(sigLength), signature.length);
        }

        uint8 hashType = 0x00;
        if (sigLength == 65) {
            hashType = uint8(signature[66]);
            if (hashType != 0x01) {
                revert InvalidWitnessData(66, 0x01, hashType);
            }
        }

        bytes32 r;
        bytes32 s;
        assembly {
            r := mload(add(signature, 34))
            s := mload(add(signature, 66))
        }

        bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2TR(message, bip340PubKeyX, hashType);
        bytes32 tweakedPubKeyX = BIP322Utils.taprootTweakPubKey(bip340PubKeyX);
        bool valid = BIP340Utils.verify(uint256(tweakedPubKeyX), uint256(r), uint256(s), msgHash);

        if (!valid) {
            revert InvalidBIP322Signature(2, sigLength);
        }

        return true;
    }

    /**
     * @notice Verify BIP-322 signature for P2WPKH (SegWit) address
     * @dev Uses ECDSA signature verification and recovers the public key
     * @param signature The witness data containing ECDSA signature and public key
     * @param bip340PubKeyX The x-only public key to verify against
     * @param message The message that was signed
     * @return True if verification succeeds
     */
    function verifyBIP322P2WPKH(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
        internal
        pure
        returns (bool)
    {
        (bytes32 r, bytes32 s, bytes memory compressedPubKey) = parseP2WPKHWitnessWithPubKey(signature);

        bytes32 pubKeyX;
        assembly {
            let dataStart := add(compressedPubKey, 32)
            pubKeyX := mload(add(dataStart, 1))
        }

        if (pubKeyX != bip340PubKeyX) {
            revert PublicKeyMismatch(bip340PubKeyX, pubKeyX);
        }

        if (!Secp256k1.isNormalizedSignature(s)) {
            revert InvalidSValue(s);
        }

        bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2WPKH(message, compressedPubKey);
        return verifyECDSARecoveryWithCompressedKey(msgHash, r, s, compressedPubKey);
    }

    function parseP2WPKHWitnessWithPubKey(bytes memory signature)
        internal
        pure
        returns (bytes32 r, bytes32 s, bytes memory compressedPubKey)
    {
        // For P2WPKH, witness contains: [signature, pubkey]
        // BIP-322 witness format: [num_items, sig_length, signature, pubkey_length, pubkey]

        if (uint8(signature[0]) != 2) {
            revert InvalidWitnessData(0, 2, uint8(signature[0]));
        }

        uint8 sigLength = uint8(signature[1]);

        // Canonical P2WPKH witness is exactly 2 (header) + sigLength
        // (DER+sighash) + 1 (pubkey length byte) + 33 (compressed pubkey)
        // bytes. The sigLength floor of 9 corresponds to the shortest
        // canonical ECDSA DER signature (0x30 0x06 0x02 0x01 <r> 0x02 0x01
        // <s>) plus the sighash byte. Reject non-canonical lengths to
        // prevent witness malleability.
        if (sigLength < 9 || signature.length != uint256(sigLength) + 36) {
            revert InvalidWitnessData(1, uint256(sigLength) + 36, signature.length);
        }

        uint256 offset = 2;

        // The signature must use the SIGHASH_ALL (0x01) flag at the end
        uint8 lastByte = uint8(signature[offset + sigLength - 1]);
        if (lastByte != 0x01) {
            revert InvalidWitnessData(offset + sigLength - 1, 0x01, lastByte);
        }
        uint8 derLength = sigLength - 1;

        // Parse DER signature
        (r, s) = parseDERSignature(signature, offset, derLength);
        offset += sigLength;

        // Extract public key
        if (uint8(signature[offset]) != 33) {
            revert InvalidWitnessData(offset, 33, uint8(signature[offset]));
        }
        offset++;

        // Get compressed public key (33 bytes) - optimized with assembly
        compressedPubKey = new bytes(33);
        assembly {
            let src := add(add(signature, 32), offset)
            let dst := add(compressedPubKey, 32)
            // Copy bytes 0..31 of the compressed pubkey
            // (= signature[offset .. offset+32)).
            mstore(dst, mload(src))
            // Copy byte 32 only. mload at src+1 reads
            // signature[offset+1 .. offset+33), whose low byte
            // (selected via byte(31, _)) is signature[offset+32].
            // mstore8 writes a single byte, keeping the destination
            // write strictly within the 33-byte buffer. Previously
            // a second `mstore` at src+32 read 32 bytes past the
            // signature tail and wrote 32 bytes past compressedPubKey.
            mstore8(add(dst, 32), byte(31, mload(add(src, 1))))
        }

        return (r, s, compressedPubKey);
    }

    function verifyECDSARecoveryWithCompressedKey(bytes32 msgHash, bytes32 r, bytes32 s, bytes memory compressedPubKey)
        internal
        pure
        returns (bool)
    {
        require(compressedPubKey.length == 33, "Invalid compressed key length");

        bytes32 expectedPubKeyX;
        assembly {
            let dataStart := add(compressedPubKey, 32)
            expectedPubKeyX := mload(add(dataStart, 1))
        }

        uint8 prefix = uint8(compressedPubKey[0]);
        require(prefix == 0x02 || prefix == 0x03, "Invalid compressed key prefix");
        uint8 expectedYParity = prefix - 0x02;

        for (uint8 v = 27; v <= 28; v++) {
            uint8 recoveryId = v - 27;
            (uint256 recoveredX, uint256 recoveredY) =
                Secp256k1.recover(uint256(msgHash), recoveryId, uint256(r), uint256(s));

            if (recoveredX != 0 && recoveredY != 0) {
                if (bytes32(recoveredX) == expectedPubKeyX) {
                    uint8 recoveredYParity = uint8(recoveredY & 1);
                    if (recoveredYParity == expectedYParity) {
                        return true;
                    }
                }
            }
        }

        revert InvalidBIP322Signature(0, 64);
    }

    function buildMessage(address owner, uint256 chainId, bytes32 action, address verifyingContract)
        private
        pure
        returns (bytes memory)
    {
        string memory actionString;
        if (action == ACTION_REGISTER) {
            actionString = "register";
        } else if (action == ACTION_SET_OPERATION_BTC_KEY) {
            actionString = "set_operation_btc_key";
        } else {
            revert InvalidAction(action);
        }
        return abi.encodePacked(
            addressToHex(owner), ":", uintToBytes(chainId), ":", actionString, ":", addressToHex(verifyingContract)
        );
    }

    /// @notice Encode the high 16 bytes of `data` as 32 lowercase ASCII hex
    ///         characters using SWAR (SIMD-within-a-register) nibble expansion.
    /// @dev Adapted from Mikhail Vladimirov's toHex16. The final correction term
    ///      uses `* 39` (0x27) instead of the original `* 7`: `* 7` maps nibbles
    ///      >= 10 to uppercase A-F, `* 39` maps them to lowercase a-f, which is the
    ///      casing the signed proof-of-possession message requires.
    /// @param data The 16 bytes to encode (held in the high half of the value)
    /// @return result 32 bytes, each an ASCII hex character for one input nibble
    function _toHex16(bytes16 data) internal pure returns (bytes32 result) {
        result = (bytes32(data) & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000)
            | (bytes32(data) & 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000) >> 64;
        result = (result & 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000)
            | (result & 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000) >> 32;
        result = (result & 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000)
            | (result & 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000) >> 16;
        result = (result & 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000)
            | (result & 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000) >> 8;
        result = (result & 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000) >> 4
            | (result & 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00) >> 8;
        result = bytes32(
            0x3030303030303030303030303030303030303030303030303030303030303030 + uint256(result)
                + (((uint256(result) + 0x0606060606060606060606060606060606060606060606060606060606060606) >> 4)
                        & 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) * 39
        );
    }

    function buildMessageWithPayload(
        address owner,
        uint256 chainId,
        bytes32 action,
        address verifyingContract,
        bytes memory payload
    ) private pure returns (bytes memory) {
        return abi.encodePacked(buildMessage(owner, chainId, action, verifyingContract), ":", bytesToHex(payload));
    }

    /// @notice Lowercase hex-encode arbitrary-length bytes, without a `0x` prefix
    /// @dev Full 16-byte chunks are encoded with `_toHex16` and written in a single MSTORE; a
    ///      trailing 1..15-byte chunk is encoded then copied char-by-char so the write stays within
    ///      `result`. Optimized form from #507 (audit follow-up); equivalent to the naive loop.
    function bytesToHex(bytes memory data) internal pure returns (bytes memory) {
        uint256 len = data.length;
        bytes memory result = new bytes(len * 2);

        uint256 offset;
        while (offset + 16 <= len) {
            bytes16 chunk;
            assembly {
                // Load data[offset..offset+16) into the high half of `chunk` and zero the low half.
                // MLOAD reads 32 bytes; bytes [offset+16, offset+32) may extend past the data
                // contents into adjacent allocated memory, so they are masked off here.
                chunk := and(
                    mload(add(add(data, 0x20), offset)),
                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
                )
            }
            bytes32 hexed = _toHex16(chunk);
            assembly {
                // offset + 16 <= len, so this 32-byte write stays within result.
                mstore(add(add(result, 0x20), mul(offset, 2)), hexed)
            }
            offset += 16;
        }

        if (offset < len) {
            bytes16 chunk;
            assembly {
                chunk := and(
                    mload(add(add(data, 0x20), offset)),
                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
                )
            }
            bytes32 hexed = _toHex16(chunk);
            uint256 tailChars = (len - offset) * 2;
            for (uint256 j = 0; j < tailChars; j++) {
                result[offset * 2 + j] = hexed[j];
            }
        }
        return result;
    }

    /// @notice Lowercase hex-encode a 20-byte address with a `0x` prefix
    /// @dev The address is left-aligned into a word; the first 16 bytes encode to
    ///      32 chars and bytes 16..19 to the leading 8 chars of the second half
    ///      (the remaining chars encode the zero padding and are dropped).
    function addressToHex(address addr) internal pure returns (bytes memory) {
        bytes32 word = bytes32(bytes20(addr));
        return abi.encodePacked("0x", _toHex16(bytes16(word)), bytes8(_toHex16(bytes16(word << 128))));
    }

    function uintToBytes(uint256 value) private pure returns (bytes memory) {
        if (value == 0) return "0";

        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }

        bytes memory buffer = new bytes(digits);
        uint256 index = digits;
        while (value != 0) {
            index--;
            buffer[index] = bytes1(uint8(48 + value % 10));
            value /= 10;
        }
        return buffer;
    }

    function parseDERSignature(bytes memory data, uint256 offset, uint256 length)
        private
        pure
        returns (bytes32 r, bytes32 s)
    {
        // Minimum valid DER: 0x30 LEN 0x02 0x01 <r> 0x02 0x01 <s> = 8 bytes
        if (length < 8 || data[offset] != 0x30) {
            revert InvalidBIP322Signature(offset, length);
        }

        // BIP-66: outer SEQUENCE length must cover the remaining bytes exactly.
        // Rejects trailing garbage and length-field/content disagreement.
        if (uint8(data[offset + 1]) != length - 2) {
            revert InvalidBIP322Signature(offset + 1, length);
        }

        uint256 end = offset + length;
        uint256 pos = offset + 2;

        (r, pos) = parseDERInteger(data, pos, end);
        (s, pos) = parseDERInteger(data, pos, end);

        if (pos != end) {
            revert InvalidBIP322Signature(pos, end);
        }

        return (r, s);
    }

    /**
     * @notice Parse a single BIP-66 canonical DER INTEGER into a bytes32 value
     * @dev Enforces minimal encoding: rejects non-canonical leading 0x00 bytes
     *      and rejects high-bit-set first bytes (negative-integer encoding)
     * @param data The buffer containing the DER-encoded signature
     * @param pos The offset of the INTEGER tag within `data`
     * @param end The exclusive upper bound within which the integer must fit
     * @return value The integer left-padded into a bytes32 (big-endian)
     * @return newPos The offset immediately after the parsed integer
     */
    function parseDERInteger(bytes memory data, uint256 pos, uint256 end)
        private
        pure
        returns (bytes32 value, uint256 newPos)
    {
        // INTEGER tag + length byte must fit within the remaining bytes
        if (pos + 2 > end || data[pos] != 0x02) {
            revert InvalidBIP322Signature(pos, end);
        }
        pos++;

        uint8 intLength = uint8(data[pos]);
        pos++;

        // secp256k1 scalars fit in 32 bytes; canonical DER allows up to 33
        // bytes when a leading 0x00 padding is required. Length 0 is invalid.
        if (intLength == 0 || intLength > 33 || pos + intLength > end) {
            revert InvalidBIP322Signature(pos, intLength);
        }

        uint8 firstByte = uint8(data[pos]);

        // High bit set on the first byte would encode a negative integer.
        // BIP-66 requires ECDSA scalars to be encoded as positive integers.
        if (firstByte & 0x80 != 0) {
            revert InvalidBIP322Signature(pos, intLength);
        }

        // A 33-byte encoding is only canonical when it is exactly 0x00 padding
        // of a 32-byte value whose high bit is set. Any other 33-byte content
        // would represent a scalar >= 2**256, which is out of range.
        if (intLength == 33 && firstByte != 0x00) {
            revert InvalidBIP322Signature(pos, intLength);
        }

        // A leading 0x00 byte is only canonical when it is strictly required
        // to keep the integer positive (next byte has its high bit set).
        // Rejecting redundant 0x00 padding enforces BIP-66 signature
        // malleability resistance.
        if (intLength > 1 && firstByte == 0x00 && uint8(data[pos + 1]) & 0x80 == 0) {
            revert InvalidBIP322Signature(pos, intLength);
        }

        uint256 valueStart = pos;
        uint8 valueLen = intLength;
        if (intLength == 33) {
            // Strip the mandatory 0x00 padding; the scalar fits in 32 bytes.
            valueStart++;
            valueLen = 32;
        }

        value = bytesToBytes32(data, valueStart, valueLen);
        newPos = pos + intLength;
    }

    function bytesToBytes32(bytes memory data, uint256 offset, uint256 length) private pure returns (bytes32 result) {
        require(length <= 32, "Length exceeds 32 bytes");
        // Defense-in-depth: callers within this library already enforce
        // offset + length <= data.length, but checking it at the unsafe-assembly
        // boundary localizes the safety property and guards against future
        // callers that might violate the invariant.
        require(offset + length <= data.length, "Out of bounds");

        assembly {
            result := mload(add(add(data, 32), offset))

            if lt(length, 32) { result := shr(mul(sub(32, length), 8), result) }
        }

        return result;
    }
}

src/protocol/lib/EthProofOfPossession.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {ECDSA} from "../../../lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "../../../lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol";

/// @title EthProofOfPossession
/// @notice Self-proof-of-possession for operation-ETH keys. A participant declaring an
///         operation-ETH key — rotating post-registration or bootstrapping one at registration —
///         must present an EIP-191 signature produced by the NEW key over a message bound to the
///         action, the new key, the admin (caller), and this contract + chain.
/// @dev The op-ETH key is the ACK signer; ACK tracking and the all-ACKed completion check key on the
///      recovered op-ETH address. Without this proof an admin could rotate onto an address it does
///      not control — e.g. another participant's op-ETH — so a single signature from that address
///      would satisfy two required ACK slots. Requiring the new key to sign makes that impossible:
///      only the holder of the private key can produce a signature that recovers to the address.
///      `address(this)` + `block.chainid` scope the proof to this registry and chain; `caller` scopes
///      it to the rotating admin; `payload` carries any role-specific binding (e.g. the app entry
///      point for keepers). Mirrors `BTCProofOfPossession.ACTION_SET_OPERATION_BTC_KEY`.
library EthProofOfPossession {
    /// @notice Action tag for the operation-ETH-key rotation proof, mirroring the BTC PoP action
    bytes32 public constant ACTION_SET_OPERATION_ETH_KEY = keccak256("set_operation_eth_key");

    /// @notice Verify that `newOpEthKey` signed the rotation message bound to `caller` and `payload`
    /// @param newOpEthKey The operation-ETH key being set; the recovered signer must equal it
    /// @param caller The participant admin the key will serve (the rotating admin, or the
    ///        registrant / listed keeper admin when the key is bootstrapped at registration)
    /// @param payload Role-specific binding bytes (empty for VP/UC, the app entry point for VK)
    /// @param signature The EIP-191 signature produced by `newOpEthKey`
    /// @return True if the signature recovers to `newOpEthKey`
    function verify(address newOpEthKey, address caller, bytes memory payload, bytes memory signature)
        internal
        view
        returns (bool)
    {
        bytes32 messageHash = keccak256(
            abi.encodePacked(ACTION_SET_OPERATION_ETH_KEY, newOpEthKey, caller, address(this), block.chainid, payload)
        );
        bytes32 ethSignedHash = MessageHashUtils.toEthSignedMessageHash(messageHash);
        return ECDSA.recover(ethSignedHash, signature) == newOpEthKey;
    }
}

src/protocol/lib/OpKeyVersionSearch.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {BTCVaultRegistryTypes} from "./types/BTCVaultRegistryTypes.sol";

/// @title OpKeyVersionSearch
/// @notice Binary search over a participant's append-only operation-key / payout version history to
///         resolve the version bonded at a given epoch in O(log n) rather than O(n).
/// @dev Correctness relies on the append-only invariant that, within a single participant's history,
///      the stored `epoch` is STRICTLY INCREASING with the version index: every append stamps a
///      freshly-bumped registry epoch onto `version = latest + 1`, and versions are contiguous
///      `1..latest` with no gaps. So "the latest version whose epoch <= target" is a monotonic
///      predicate and can be found by binary search.
///
///      This replaces a linear newest->oldest scan, which is a DoS vector: the walk length equals the
///      number of rotations a participant made AFTER a vault was bonded, and the participant controls
///      its own rotation count. Enough rotations make a vault's redeem / ACK / signature-verify walk
///      exceed the block gas limit, permanently locking that vault (and its consumed application caps)
///      — a griefing vector against depositors bonded to a compromised participant. Binary search
///      bounds the work at `ceil(log2(latest)) <= 16` reads (version is `uint16`), independent of the
///      rotation count. Result is byte-identical to the linear scan.
///      Returns `0` when no stored version qualifies, so the caller falls back to the derived v0
///      (registration key / admin / BIP-86 default).
library OpKeyVersionSearch {
    /// @notice Largest operation-BTC-key version in `[1, latest]` whose epoch <= `epoch`, else 0
    function findAtEpoch(
        mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion) storage versions,
        uint16 latest,
        uint64 epoch
    ) internal view returns (uint16) {
        uint256 lo = 1;
        uint256 hi = latest;
        uint256 found = 0;
        while (lo <= hi) {
            uint256 mid = (lo + hi) >> 1;
            if (versions[uint16(mid)].epoch <= epoch) {
                found = mid;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return uint16(found);
    }

    /// @notice Largest operation-ETH-key version in `[1, latest]` whose epoch <= `epoch`, else 0
    function findAtEpoch(
        mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion) storage versions,
        uint16 latest,
        uint64 epoch
    ) internal view returns (uint16) {
        uint256 lo = 1;
        uint256 hi = latest;
        uint256 found = 0;
        while (lo <= hi) {
            uint256 mid = (lo + hi) >> 1;
            if (versions[uint16(mid)].epoch <= epoch) {
                found = mid;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return uint16(found);
    }

    /// @notice Largest payout-script version in `[1, latest]` whose epoch <= `epoch`, else 0
    function findAtEpoch(
        mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion) storage versions,
        uint16 latest,
        uint64 epoch
    ) internal view returns (uint16) {
        uint256 lo = 1;
        uint256 hi = latest;
        uint256 found = 0;
        while (lo <= hi) {
            uint256 mid = (lo + hi) >> 1;
            if (versions[uint16(mid)].epoch <= epoch) {
                found = mid;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return uint16(found);
    }
}

src/protocol/lib/helpers/BIP322Utils.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {BIP341} from "../taproot/BIP341.sol";

/**
 * @title BIP322Utils
 * @notice Utility functions for BIP-322 signature verification
 * @dev Implements BIP-322 transaction construction and sighash calculation
 * @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
 * @dev NOTE: for wallet compatibility SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
 * for Taproot addresses; only SIGHASH_ALL is supported for P2WPKH addresses.
 */
library BIP322Utils {
    /// @notice Maximum scriptPubKey length encodable as a single-byte Bitcoin
    /// compact size. Values 0xFD-0xFF are reserved as multi-byte size
    /// prefixes, so a 1-byte length cast is only canonical for lengths
    /// 0..0xFC (= 252).
    uint256 internal constant MAX_SINGLE_BYTE_COMPACT_SIZE = 252;

    /// @notice Thrown when a scriptPubKey exceeds the single-byte compact-size
    /// length encoding range used by buildToSpendTx and calculateTaprootSigHash.
    error ScriptPubKeyTooLong();

    /**
     * @notice Compute the Taproot tweaked output key for key-path spending
     * @dev For key-path only (no script tree), output_key = internal_key + hash("TapTweak" || internal_key) * G
     * @dev Uses BIP341 library for standardized Taproot key tweaking
     * @param internalPubKeyX The x-only internal public key
     * @return The x-only tweaked output key
     */
    function taprootTweakPubKey(bytes32 internalPubKeyX) internal pure returns (bytes32) {
        // Use BIP341.computeOutputKey for key-path only spending (empty merkle root)
        (bytes32 outputKey,) = BIP341.computeOutputKey(internalPubKeyX, "");
        return outputKey;
    }

    /**
     * @notice Calculate BIP-340 tagged hash for BIP-322
     * @dev Implements: sha256(sha256(tag) || sha256(tag) || msg)
     * @param message The message to hash
     * @return The tagged hash
     */
    function getBIP340TaggedHash(bytes memory message) internal pure returns (bytes32) {
        bytes32 tagHash = sha256(abi.encodePacked("BIP0322-signed-message"));
        return sha256(abi.encodePacked(tagHash, tagHash, message));
    }

    /**
     * @notice Convert internal public key to P2TR scriptPubKey
     * @param bip340PubKeyX The x-only internal public key
     * @return The P2TR scriptPubKey
     */
    function pubKeyToP2TRScriptPubKey(bytes32 bip340PubKeyX) internal pure returns (bytes memory) {
        // P2TR: OP_1 OP_PUSHBYTES_32 <taproot_output_key>
        // For key-path only spending (no script tree), we must use the TWEAKED output key
        bytes32 tweakedOutputKey = taprootTweakPubKey(bip340PubKeyX);
        return abi.encodePacked(uint8(0x51), uint8(0x20), tweakedOutputKey);
    }

    /**
     * @notice Build to_spend transaction and return its txid
     * @param messageHash The BIP-340 tagged hash of the message
     * @param scriptPubKey The scriptPubKey for the output
     * @return The transaction ID
     */
    function buildToSpendTx(bytes32 messageHash, bytes memory scriptPubKey) internal pure returns (bytes32) {
        if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();

        // to_spend transaction structure per BIP-322:
        // version: 4 bytes (0x00000000)
        // input count: 1 byte (0x01)
        // input:
        //   - txid: 32 bytes (0x00...00)
        //   - vout: 4 bytes (0xffffffff)
        //   - scriptSig: varint + OP_0 OP_PUSHBYTES_32 <messageHash>
        //   - sequence: 4 bytes (0x00000000)
        // output count: 1 byte (0x01)
        // output:
        //   - value: 8 bytes (0x0000000000000000)
        //   - scriptPubKey: varint + scriptPubKey
        // locktime: 4 bytes (0x00000000)

        bytes memory scriptSig = abi.encodePacked(uint8(0x00), uint8(0x20), messageHash);
        uint8 scriptSigLen = uint8(scriptSig.length);

        // NOTE: All integers must be in little-endian byte order per Bitcoin protocol
        bytes memory btcTx = abi.encodePacked(
            hex"00000000", // version
            uint8(0x01), // input count
            bytes32(0), // input txid (all zeros)
            hex"ffffffff", // input vout (0xffffffff, LE)
            scriptSigLen, // scriptSig length
            scriptSig, // scriptSig
            hex"00000000", // sequence
            uint8(0x01), // output count
            hex"0000000000000000", // output value
            uint8(scriptPubKey.length), // scriptPubKey length
            scriptPubKey, // scriptPubKey
            hex"00000000" // locktime
        );

        // Return double SHA-256 (Bitcoin txid)
        return sha256(abi.encodePacked(sha256(btcTx)));
    }

    /**
     * @notice Calculate BIP-341 Taproot sighash for BIP-322 context
     * @dev This function is specifically designed for BIP-322 signature verification
     * @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
     * @dev This is NOT a generic BIP-341 sighash implementation - use only for BIP-322 verification
     * @dev with support for SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
     * @param toSpendTxid The txid being spent
     * @param scriptPubKey The scriptPubKey being spent
     * @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
     * @return The sighash
     */
    function calculateTaprootSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey, uint8 hashType)
        internal
        pure
        returns (bytes32)
    {
        // BIP-341 signature message format (SIGHASH_ALL or SIGHASH_DEFAULT):
        // epoch (1) + hash_type (1) + version (4) + locktime (4) +
        // sha_prevouts (32) + sha_amounts (32) + sha_scriptpubkeys (32) + sha_sequences (32) + sha_outputs (32) +
        // spend_type (1) + input_index (4)
        //
        // NOTE: SIGHASH_ALL (0x01) and SIGHASH_DEFAULT (0x00) commit to ALL prevouts
        // NOTE: For BIP-322, we support both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01)
        // NOTE: BIP-341 requires compact size prefixes for scriptPubKey serialization in sha_scriptpubkeys
        // NOTE: BIP-322 toSign transaction uses sequence 0

        // Validate sighash type: only SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
        require(hashType == 0x00 || hashType == 0x01, "Invalid sighash type");

        if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();

        bytes memory sigMsg = abi.encodePacked(
            uint8(0x00), // epoch
            hashType, // hash_type (SIGHASH_DEFAULT = 0x00 or SIGHASH_ALL = 0x01)
            hex"00000000", // nVersion
            hex"00000000", // nLockTime
            sha256(abi.encodePacked(toSpendTxid, hex"00000000")), // sha_prevouts
            sha256(abi.encodePacked(hex"0000000000000000")), // sha_amounts
            sha256(abi.encodePacked(uint8(scriptPubKey.length), scriptPubKey)), // sha_scriptpubkeys (with compact size)
            sha256(abi.encodePacked(hex"00000000")), // sha_sequences (sequence is 0)
            sha256(abi.encodePacked(hex"0000000000000000", uint8(1), uint8(0x6a))), // sha_outputs (value || OP_RETURN)
            uint8(0x00), // spend_type (key-path, no annex)
            hex"00000000" // input_index (always 0)
        );

        // Return tagged hash "TapSighash"
        bytes32 tagHash = sha256(abi.encodePacked("TapSighash"));
        return sha256(abi.encodePacked(tagHash, tagHash, sigMsg));
    }

    /**
     * @notice Calculate BIP-143 SegWit v0 sighash for P2WPKH in BIP-322 context
     * @dev This function is specifically designed for BIP-322 signature verification
     * @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
     * @dev This is NOT a generic BIP-143 sighash implementation - use only for BIP-322 verification
     * @param toSpendTxid The txid being spent
     * @param scriptPubKey The scriptPubKey being spent (P2WPKH witness program: OP_0 <20-byte-hash>)
     * @return The sighash
     */
    function calculateSegwitSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey) internal pure returns (bytes32) {
        // BIP-143 sighash for witness v0 (P2WPKH)
        // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
        //
        // IMPORTANT: For P2WPKH, the scriptCode is not the witness program itself,
        // but a P2PKH-style script: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG

        // Extract the 20-byte hash from scriptPubKey (skip OP_0 and length byte)
        // scriptPubKey format: [OP_0 (0x00)] [0x14] [20-byte-hash]
        require(scriptPubKey.length == 22, "Invalid P2WPKH scriptPubKey length");
        require(uint8(scriptPubKey[0]) == 0x00 && uint8(scriptPubKey[1]) == 0x14, "Invalid P2WPKH scriptPubKey format");

        bytes20 pubKeyHash;
        assembly {
            pubKeyHash := mload(add(scriptPubKey, 34)) // 32 (length prefix) + 2 (OP_0 + 0x14)
        }

        // Build P2PKH-style scriptCode: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
        bytes memory scriptCode = abi.encodePacked(
            uint8(0x76), // OP_DUP
            uint8(0xa9), // OP_HASH160
            uint8(0x14), // Push 20 bytes
            pubKeyHash,
            uint8(0x88), // OP_EQUALVERIFY
            uint8(0xac) // OP_CHECKSIG
        );

        // Build BIP-143 sighash in parts to avoid stack too deep
        // NOTE: BIP-143 uses double SHA256 for hashPrevouts, hashSequence, and hashOutputs
        // NOTE: All integers must be in little-endian byte order per Bitcoin protocol
        bytes32 hashPrevouts = sha256(
            abi.encodePacked(
                sha256(
                    abi.encodePacked(
                        toSpendTxid,
                        hex"00000000" // outpoint index
                    )
                )
            )
        );
        bytes32 hashSequence = sha256(
            abi.encodePacked(
                sha256(
                    abi.encodePacked(
                        hex"00000000" // sequence
                    )
                )
            )
        );
        bytes32 hashOutputs = sha256(
            abi.encodePacked(
                sha256(
                    abi.encodePacked(
                        hex"0000000000000000", // value
                        uint8(1), // scriptPubKey length
                        uint8(0x6a) // OP_RETURN
                    )
                )
            )
        );

        bytes memory part1 = abi.encodePacked(
            hex"00000000", // nVersion
            hashPrevouts, // hashPrevouts (double SHA256)
            hashSequence, // hashSequence (double SHA256)
            toSpendTxid, // outpoint hash
            hex"00000000", // outpoint index
            uint8(scriptCode.length), // scriptCode length
            scriptCode // scriptCode (P2PKH format)
        );

        bytes memory part2 = abi.encodePacked(
            hex"0000000000000000", // value
            hex"00000000", // nSequence
            hashOutputs, // hashOutputs (double SHA256)
            hex"00000000", // nLockTime
            hex"01000000" // sighash type (SIGHASH_ALL = 1, LE)
        );

        bytes memory sigMsg = abi.encodePacked(part1, part2);
        return sha256(abi.encodePacked(sha256(sigMsg)));
    }

    /**
     * @notice Calculate BIP-322 sighash for P2TR address
     * @param message The message being signed
     * @param bip340PubKeyX The x-only public key
     * @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
     * @return The sighash to verify
     */
    function calculateBIP322SigHashP2TR(bytes memory message, bytes32 bip340PubKeyX, uint8 hashType)
        internal
        pure
        returns (bytes32)
    {
        // Get the BIP-340 tagged hash of the message
        bytes32 messageHash = getBIP340TaggedHash(message);

        // Build the scriptPubKey from the public key
        bytes memory scriptPubKey = pubKeyToP2TRScriptPubKey(bip340PubKeyX);

        // Build to_spend transaction
        bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);

        // Calculate BIP-341 sighash for the to_sign transaction
        return calculateTaprootSigHash(toSpendTxid, scriptPubKey, hashType);
    }

    /**
     * @notice Calculate BIP-322 sighash for P2WPKH address using compressed public key
     * @param message The message being signed
     * @param compressedPubKey The 33-byte compressed public key from witness
     * @return The sighash to verify
     */
    function calculateBIP322SigHashP2WPKH(bytes memory message, bytes memory compressedPubKey)
        internal
        pure
        returns (bytes32)
    {
        require(compressedPubKey.length == 33, "Invalid compressed public key length");

        // Get the BIP-340 tagged hash of the message
        bytes32 messageHash = getBIP340TaggedHash(message);

        // Build the scriptPubKey from the compressed public key
        // P2WPKH: OP_0 OP_PUSHBYTES_20 <HASH160(pubkey)>
        bytes32 sha = sha256(compressedPubKey);
        bytes20 hash160 = ripemd160(abi.encodePacked(sha));
        bytes memory scriptPubKey = abi.encodePacked(uint8(0x00), uint8(0x14), hash160);

        // Build to_spend transaction
        bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);

        // Calculate BIP-143 sighash for the to_sign transaction
        return calculateSegwitSigHash(toSpendTxid, scriptPubKey);
    }
}

src/protocol/lib/helpers/BIP340Utils.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";

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

/**
 * @title BIP340Utils
 * @notice Library for BIP-340 Schnorr signature verification on secp256k1
 * @dev Uses an ecrecover optimization technique for efficient verification
 */
// Based on https://hackmd.io/@nZ-twauPRISEa6G9zg3XRw/SyjJzSLt9
library BIP340Utils {
    /**
     * @notice Verify a BIP-340 Schnorr signature
     * @dev Uses the ecrecover hack to verify a schnorr signature more efficiently
     * @param px The x-coordinate of the public key
     * @param rx The x-coordinate of the R point in the signature
     * @param s The s value of the signature
     * @param m The message hash
     * @return True if the signature is valid
     */
    function verify(uint256 px, uint256 rx, uint256 s, bytes32 m) public pure returns (bool) {
        // Check pubkey, rx, and s are in-range.
        if (px >= Secp256k1.P || rx >= Secp256k1.P || s >= Secp256k1.N) {
            return false;
        }

        (address exp, bool ok) = convToFakeAddr(rx);
        if (!ok) {
            return false;
        }

        uint256 e = computeChallenge(bytes32(rx), bytes32(px), m);
        bytes32 sp = bytes32(Secp256k1.N - mulmod(s, px, Secp256k1.N));
        bytes32 ep = bytes32(Secp256k1.N - mulmod(e, px, Secp256k1.N));

        // 27 apparently used to signal even parity (which it will always have).
        address rvh = ecrecover(sp, 27, bytes32(px), ep);
        return rvh == exp; // if recovery fails we fail anyways
    }

    /**
     * @notice Compute BIP-340 challenge value
     * @dev Computes e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n
     * @param rx The x-coordinate of the R point as bytes32
     * @param px The x-coordinate of the public key as bytes32
     * @param m The message hash
     * @return The challenge value modulo curve order
     */
    function computeChallenge(bytes32 rx, bytes32 px, bytes32 m) internal pure returns (uint256) {
        // Precomputed `sha256("BIP0340/challenge")`.
        //
        // Saves ~10k gas, mostly from byte shuffling to prepare the call.
        //bytes32 tag = sha256("BIP0340/challenge");
        bytes32 tag = 0x7bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c;

        // Let e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n.
        return uint256(sha256(abi.encodePacked(tag, tag, rx, px, m))) % Secp256k1.N;
    }

    /**
     * @notice Lift x-coordinate to full point on secp256k1 curve
     * @dev Given an x coordinate, returns the y coordinate of an even point on the secp256k1 curve
     * @param _x The x-coordinate to lift
     * @return y The y-coordinate of the even point
     * @return success True if the operation was successful
     */
    function liftX(uint256 _x) internal pure returns (uint256, bool) {
        uint256 _pp = Secp256k1.P;
        uint256 _aa = Secp256k1.A;
        uint256 _bb = Secp256k1.B;

        if (_x >= _pp) {
            return (0, false);
        }

        // Use EllipticCurve library to derive y-coordinate (0x02 for even y)
        uint256 y = EllipticCurve.deriveY(0x02, _x, _aa, _bb, _pp);
        if (!EllipticCurve.isOnCurve(_x, y, _aa, _bb, _pp)) {
            return (0, false);
        }

        return (y, true);
    }

    /**
     * @notice Convert Jacobian x-coordinate to affine coordinates
     * @dev Internal function for doing the affine conversion for only the x coordinate
     * @param _x The x-coordinate in Jacobian form
     * @param _z The z-coordinate in Jacobian form
     * @param _pp The prime modulus
     * @return The x-coordinate in affine form
     */
    function xToAffine(uint256 _x, uint256 _z, uint256 _pp) internal pure returns (uint256) {
        uint256 zInv = EllipticCurve.invMod(_z, _pp);
        uint256 zInv2 = mulmod(zInv, zInv, _pp);
        return mulmod(_x, zInv2, _pp);
    }

    /**
     * @notice Convert BIP-340 public key x-coordinate to Ethereum address format
     * @dev Converts a BIP340 pubkey X coord to what it would look like as an Ethereum address
     * @param px The x-coordinate of the BIP-340 public key
     * @return addr The pseudo-Ethereum address
     * @return success True if the conversion was successful
     */
    function convToFakeAddr(uint256 px) internal pure returns (address, bool) {
        (uint256 py, bool ok) = liftX(px);
        if (!ok) {
            return (address(0), false);
        }
        bytes32 h = keccak256(abi.encodePacked(bytes32(px), bytes32(py)));
        return (address(uint160(uint256(h))), true);
    }
}

src/protocol/lib/helpers/CompactSize.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title CompactSize
 * @notice Bitcoin CompactSize integer encoding/decoding utilities
 * @dev Implements Bitcoin's variable-length integer format used in transaction serialization
 * @dev Reference: https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
 */
library CompactSize {
    error InvalidCompactSize(uint256 offset, uint8 prefix, uint64 value, uint64 minValue);
    error BufferTooShort(uint256 offset, uint256 requiredLength, uint256 availableLength);

    // ============ Encoding Functions ============

    /**
     * @notice Encode an integer as Bitcoin CompactSize format
     * @param value The integer to encode (uint64)
     * @return Encoded bytes in CompactSize format
     * @dev Format:
     *      - value < 0xFD: [value] (1 byte)
     *      - value <= 0xFFFF: [0xFD][value as LE uint16] (3 bytes)
     *      - value <= 0xFFFFFFFF: [0xFE][value as LE uint32] (5 bytes)
     *      - value > 0xFFFFFFFF: [0xFF][value as LE uint64] (9 bytes)
     */
    function encode(uint64 value) internal pure returns (bytes memory) {
        if (value < 0xFD) {
            // Single byte
            return abi.encodePacked(uint8(value));
        } else if (value <= 0xFFFF) {
            // 0xFD + 2 bytes (little-endian uint16)
            return abi.encodePacked(uint8(0xFD), uint8(value), uint8((value >> 8)));
        } else if (value <= 0xFFFFFFFF) {
            // 0xFE + 4 bytes (little-endian uint32)
            return abi.encodePacked(
                uint8(0xFE), uint8(value), uint8((value >> 8)), uint8((value >> 16)), uint8((value >> 24))
            );
        } else {
            // 0xFF + 8 bytes (little-endian uint64)
            return abi.encodePacked(
                uint8(0xFF),
                uint8(value),
                uint8((value >> 8)),
                uint8((value >> 16)),
                uint8((value >> 24)),
                uint8((value >> 32)),
                uint8((value >> 40)),
                uint8((value >> 48)),
                uint8((value >> 56))
            );
        }
    }

    /**
     * @notice Get the encoded length for a given value
     * @param value The value to measure
     * @return Length in bytes of the CompactSize encoding
     */
    function encodedLength(uint64 value) internal pure returns (uint8) {
        if (value < 0xFD) return 1;
        if (value <= 0xFFFF) return 3;
        if (value <= 0xFFFFFFFF) return 5;
        return 9;
    }

    // ============ Decoding Functions ============

    /**
     * @notice Decode CompactSize integer from bytes
     * @param data The bytes to decode from
     * @param offset Starting position in the data
     * @return value The decoded uint64 value
     * @return newOffset Position immediately after the decoded CompactSize
     * @dev Reverts if data is malformed or insufficient
     */
    function decode(bytes memory data, uint256 offset) internal pure returns (uint64 value, uint256 newOffset) {
        if (offset >= data.length) revert BufferTooShort(offset, offset + 1, data.length);

        uint8 firstByte = uint8(data[offset]);

        if (firstByte < 0xFD) {
            // Single byte value
            return (uint64(firstByte), offset + 1);
        } else if (firstByte == 0xFD) {
            // 2-byte value (uint16)
            if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
            value = readUint16LE(data, offset + 1);
            if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD); // Non-canonical encoding
            return (value, offset + 3);
        } else if (firstByte == 0xFE) {
            // 4-byte value (uint32)
            if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
            value = readUint32LE(data, offset + 1);
            if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000); // Non-canonical encoding
            return (value, offset + 5);
        } else {
            // 8-byte value (uint64)
            if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
            value = readUint64LE(data, offset + 1);
            if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000); // Non-canonical encoding
            return (value, offset + 9);
        }
    }

    /**
     * @notice Decode CompactSize from calldata
     * @param data The calldata to decode from
     * @param offset Starting position
     * @return value The decoded uint64 value
     * @return newOffset Position immediately after the decoded CompactSize
     */
    function decodeCalldata(bytes calldata data, uint256 offset)
        internal
        pure
        returns (uint64 value, uint256 newOffset)
    {
        if (offset >= data.length) {
            revert BufferTooShort(offset, offset + 1, data.length);
        }

        uint8 firstByte = uint8(data[offset]);

        if (firstByte < 0xFD) {
            return (uint64(firstByte), offset + 1);
        } else if (firstByte == 0xFD) {
            if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
            value = readUint16LECalldata(data, offset + 1);
            if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD);
            return (value, offset + 3);
        } else if (firstByte == 0xFE) {
            if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
            value = readUint32LECalldata(data, offset + 1);
            if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000);
            return (value, offset + 5);
        } else {
            if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
            value = readUint64LECalldata(data, offset + 1);
            if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000);
            return (value, offset + 9);
        }
    }

    // ============ Little-Endian Reading Helpers ============

    /**
     * @notice Read little-endian uint16 from bytes
     */
    function readUint16LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
    }

    /**
     * @notice Read little-endian uint32 from bytes
     */
    function readUint32LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
    }

    /**
     * @notice Read little-endian uint64 from bytes
     */
    function readUint64LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
            | (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
            | (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
    }

    /**
     * @notice Read little-endian uint16 from calldata
     */
    function readUint16LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
    }

    /**
     * @notice Read little-endian uint32 from calldata
     */
    function readUint32LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
    }

    /**
     * @notice Read little-endian uint64 from calldata
     */
    function readUint64LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
        return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
            | (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
            | (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
            | (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
    }
}

src/protocol/lib/helpers/Secp256k1.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";

/**
 * @title Secp256k1 public key recovery Library
 * @dev Library providing arithmetic operations to recover the signer public key EC point from secp256k1 signed messages in Solidity
 */
library Secp256k1 {
    // Curve Constants (secp256k1)
    uint256 internal constant A = 0;
    uint256 internal constant B = 7;
    uint256 internal constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
    uint256 internal constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
    uint256 internal constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
    uint256 internal constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;

    /// @notice secp256k1 curve order divided by 2 (for BIP-62 compliance)
    bytes32 internal constant N_DIV_2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    /// @dev recovers signer public key point value.
    /// @param digest hashed message
    /// @param v recovery id (0 or 1)
    /// @param r first 32 bytes of signature
    /// @param s last 32 bytes of signature
    /// @return (x, y) EC point coordinates of the recovered public key
    function recover(uint256 digest, uint8 v, uint256 r, uint256 s) internal pure returns (uint256, uint256) {
        // Validate scalar ranges and recovery id up front. We restrict v to
        // {0, 1}, which means the standard ECDSA x = r + (v >> 1) * N (mod P)
        // collapses to x = r. Since N < P and r >= N is rejected, r already
        // satisfies r < P, so no further reduction is required.
        if (r == 0 || r >= N || s == 0 || s >= N || v > 1) {
            return (0, 0);
        }
        uint256 x = r;
        uint256 rInv = EllipticCurve.invMod(r, N);

        // v encodes the parity of y directly: 0 -> 0x02 (even), 1 -> 0x03 (odd).
        uint256 y = EllipticCurve.deriveY(uint8(0x02 + v), x, A, B, P);

        // deriveY returns a value for any x via the (p+1)/4 shortcut, even when
        // x lives on the twist rather than secp256k1. Reject off-curve points so
        // downstream arithmetic only operates on secp256k1 group elements.
        if (!EllipticCurve.isOnCurve(x, y, A, B, P)) {
            return (0, 0);
        }

        // Q = rInv * (s * R - digest * G)
        // Compute s * R
        (uint256 qx, uint256 qy, uint256 qz) = EllipticCurve.jacMul(mulmod(rInv, s, N), x, y, 1, A, P);
        // Compute -digest * G
        uint256 digestModN = digest % N;
        (uint256 qx2, uint256 qy2, uint256 qz2) = EllipticCurve.jacMul(mulmod(rInv, N - digestModN, N), GX, GY, 1, A, P);
        // Add the two points
        (uint256 qx3, uint256 qy3, uint256 qz3) = EllipticCurve.jacAdd(qx, qy, qz, qx2, qy2, qz2, P);

        return EllipticCurve.toAffine(qx3, qy3, qz3, P);
    }

    /**
     * @notice Validate that a signature S value is normalized (BIP-62)
     * @param s The s value from the signature
     * @return True if s is in the lower half of the curve order
     */
    function isNormalizedSignature(bytes32 s) internal pure returns (bool) {
        return uint256(s) <= uint256(N_DIV_2);
    }
}

src/protocol/lib/taproot/BIP341.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";

import {TaprootConstants} from "./TaprootConstants.sol";
import {CompactSize} from "../helpers/CompactSize.sol";

/**
 * @title BIP341
 * @notice BIP341 Taproot cryptographic primitives
 * @dev Implements tagged hashing, x-only public key operations, and Taproot output key computation
 * @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
 */
library BIP341 {
    error InvalidPoint(uint256 x, uint256 y);
    error InvalidXOnlyKey(bytes32 xOnly);
    error InvalidControlBlock(uint256 length, uint256 remainder);
    error InvalidBase(uint256 base, uint256 modulus);

    /// @dev Control-block byte 0 packs the leaf version in the high 7 bits and
    ///      the output-key y-parity in the low bit.
    uint8 internal constant PARITY_MASK = 0x01;
    uint8 internal constant LEAF_VERSION_MASK = 0xfe;

    // ============ Tagged Hash Functions ============

    /**
     * @notice Compute BIP340-style tagged hash: SHA256(SHA256(tag) || SHA256(tag) || data)
     * @param tag The domain separation tag as raw UTF-8 bytes (not padded)
     * @param data The data to hash
     * @return The 32-byte tagged hash
     * @dev This prevents collision between different hash contexts
     * @dev Reference: BIP-340 tagged hashes use raw tag bytes, not padded to 32 bytes
     */
    function taggedHash(bytes memory tag, bytes memory data) internal pure returns (bytes32) {
        bytes32 tagHash = sha256(tag);
        return sha256(abi.encodePacked(tagHash, tagHash, data));
    }

    /**
     * @notice Compute TapTweak tagged hash for Taproot output key computation
     * @param internalPubKey The 32-byte x-only internal public key
     * @param merkleRoot The merkle root of the TapTree (empty bytes for key-path only, 32 bytes for script-path)
     * @return The tagged hash used for tweaking
     * @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
     */
    function tapTweakHash(bytes32 internalPubKey, bytes memory merkleRoot) internal pure returns (bytes32) {
        return taggedHash(TaprootConstants.TAG_TAPTWEAK, abi.encodePacked(internalPubKey, merkleRoot));
    }

    /**
     * @notice Compute TapLeaf tagged hash for a script leaf
     * @param leafVersion The leaf version byte (0xC0 for Tapscript v0)
     * @param script The script bytes
     * @return The leaf hash
     * @dev Format: TapLeaf || leaf_version || compact_size(script_len) || script
     */
    function tapLeafHash(uint8 leafVersion, bytes memory script) internal pure returns (bytes32) {
        // Encode script length using Bitcoin's CompactSize format (little-endian)
        bytes memory scriptLength = CompactSize.encode(uint64(script.length));
        return taggedHash(TaprootConstants.TAG_TAPLEAF, abi.encodePacked(leafVersion, scriptLength, script));
    }

    /**
     * @notice Compute TapBranch tagged hash for merkle tree internal node
     * @param left Left child hash
     * @param right Right child hash
     * @return The branch hash with lexicographic sorting applied
     * @dev Hashes are sorted to ensure deterministic tree construction
     */
    function tapBranchHash(bytes32 left, bytes32 right) internal pure returns (bytes32) {
        // Lexicographic ordering: compare as big-endian integers
        if (uint256(left) < uint256(right)) {
            return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(left, right));
        } else {
            return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(right, left));
        }
    }

    // ============ X-Only Public Key Operations ============

    /**
     * @notice Lift x-only public key to full (x, y) curve point
     * @param xOnly The 32-byte x-coordinate
     * @return x The x-coordinate (same as input)
     * @return y The y-coordinate (even parity, i.e., y mod 2 == 0)
     * @dev Uses secp256k1 curve equation: y^2 = x^3 + b (b = TaprootConstants.BB)
     * @dev Always returns the even y-coordinate per BIP340 convention
     */
    function liftX(bytes32 xOnly) internal pure returns (uint256 x, uint256 y) {
        x = uint256(xOnly);

        // Derive y from x using EllipticCurve library (0x02 = even parity per BIP340)
        y = EllipticCurve.deriveY(
            0x02, // even parity prefix
            x,
            TaprootConstants.AA,
            TaprootConstants.BB,
            TaprootConstants.PP
        );

        // Verify point is on curve
        if (!EllipticCurve.isOnCurve(x, y, TaprootConstants.AA, TaprootConstants.BB, TaprootConstants.PP)) {
            revert InvalidXOnlyKey(xOnly);
        }

        return (x, y);
    }

    /**
     * @notice Check if a point's y-coordinate is even (quadratic residue)
     * @param y The y-coordinate
     * @return True if y is even (y mod 2 == 0)
     */
    function hasEvenY(uint256 y) internal pure returns (bool) {
        return (y & 1) == 0;
    }

    /**
     * @notice Validate if an x-only public key represents a valid secp256k1 curve point
     * @param xOnly The 32-byte x-coordinate to validate
     * @return True if the x-coordinate has a corresponding valid y-coordinate on the curve
     * @dev This ensures the key can be lifted to a full curve point without reverting
     * @dev Uses inline computation to check if y^2 = x^3 + b (b = TaprootConstants.BB) has a valid square root
     */
    function isValidXOnlyKey(bytes32 xOnly) internal pure returns (bool) {
        uint256 x = uint256(xOnly);
        uint256 pp = TaprootConstants.PP;

        // x must be a canonical secp256k1 field element that lifts to a curve point
        if (x == 0 || x >= pp) return false;

        // Compute y^2 = x^3 + b (mod p), b = TaprootConstants.BB
        uint256 y2 = addmod(
            mulmod(x, mulmod(x, x, pp), pp),
            TaprootConstants.BB, // secp256k1 curve parameter b
            pp
        );

        // Check if y2 is a quadratic residue (has a square root) using Euler's criterion
        // For prime p, y2 is a QR iff y2^((p-1)/2) ≡ 1 (mod p)
        // For secp256k1, (p-1)/2 can be computed
        uint256 euler = expPod(y2, TaprootConstants.PP_S1D2, pp);

        // If Euler's criterion returns 1, then y2 has a square root
        return euler == 1;
    }

    /**
     * @notice Modular exponentiation helper
     * @param base The base
     * @param exponent The exponent
     * @param modulus The modulus
     * @return result base^exponent mod modulus
     */
    function expPod(uint256 base, uint256 exponent, uint256 modulus) internal pure returns (uint256 result) {
        if (base >= modulus) revert InvalidBase(base, modulus);

        result = 1;
        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result = mulmod(result, base, modulus);
            }
            exponent = exponent >> 1;
            base = mulmod(base, base, modulus);
        }
    }

    /**
     * @notice Extract x-only public key from point
     * @param x The x-coordinate
     * @param y The y-coordinate
     * @return The 32-byte x-only public key
     */
    function toXOnly(uint256 x, uint256 y) internal pure returns (bytes32) {
        // Unused y parameter - included for API clarity
        y; // silence compiler warning
        return bytes32(x);
    }

    // ============ Taproot Output Key Computation ============

    /**
     * @notice Compute Taproot output key P from internal key Q and merkle root
     * @param internalPubKey The 32-byte x-only internal public key Q
     * @param merkleRoot The merkle root h (empty bytes for key-path only, 32 bytes for script-path)
     * @return outputKey The 32-byte x-only output public key P
     * @return outputKeyYIsOdd True if the output key's y-coordinate is odd
     * @dev Formula: P = Q + int(hash_TapTweak(Q || h)) * G
     * @dev Reference: BIP341 "Constructing and spending Taproot outputs"
     * @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
     */
    function computeOutputKey(bytes32 internalPubKey, bytes memory merkleRoot)
        internal
        pure
        returns (bytes32 outputKey, bool outputKeyYIsOdd)
    {
        // 1. Lift internal key Q to curve point
        (uint256 qx, uint256 qy) = liftX(internalPubKey);

        // 2. Compute tweak t = int(hash_TapTweak(Q || h)) mod n
        // Note: Following btcd implementation which automatically
        // performs modulo N reduction rather than failing on overflow.
        bytes32 tweakHash = tapTweakHash(internalPubKey, merkleRoot);
        uint256 t = uint256(tweakHash) % TaprootConstants.NN;

        // 3. Compute t*G (scalar multiplication of generator by tweak)
        (uint256 tGx, uint256 tGy) =
            EllipticCurve.ecMul(t, TaprootConstants.GX, TaprootConstants.GY, TaprootConstants.AA, TaprootConstants.PP);

        // 4. Compute P = Q + t*G (point addition)
        (uint256 px, uint256 py) = EllipticCurve.ecAdd(qx, qy, tGx, tGy, TaprootConstants.AA, TaprootConstants.PP);

        // Verify result is valid point
        if (px == 0 && py == 0) {
            revert InvalidPoint(px, py);
        }

        // 5. Return x-only representation of P and its y-coordinate parity
        return (toXOnly(px, py), !hasEvenY(py));
    }

    /**
     * @notice Verify a Taproot output key matches expected internal key and merkle root
     * @param outputKey The claimed x-only output key
     * @param internalPubKey The internal public key
     * @param merkleRoot The merkle root (empty bytes for key-path only, 32 bytes for script-path)
     * @return True if outputKey == computeOutputKey(internalPubKey, merkleRoot)
     */
    function verifyOutputKey(bytes32 outputKey, bytes32 internalPubKey, bytes memory merkleRoot)
        internal
        pure
        returns (bool)
    {
        (bytes32 computed,) = computeOutputKey(internalPubKey, merkleRoot);
        return outputKey == computed;
    }

    // ============ Taproot Leaf Commitment Verification ============

    /**
     * @notice Verify that a script is committed in a Taproot output via control block
     * @param controlBlock The control block containing: leafVersion, parity, internalKey, merkleProof
     * @param witnessProgram The 32-byte output key from the scriptPubKey (P)
     * @param script The script to verify
     * @return True if script is committed in the Taproot output
     * @dev This is the core Taproot verification matching Bitcoin's txscript.VerifyTaprootLeafCommitment
     * @dev Control block format: [leafVersion + parity (1 byte)] [internalKey (32 bytes)] [merkleProof (0 or more 32-byte hashes)]
     * @dev Reference: https://github.com/btcsuite/btcd/blob/v0.24.2/txscript/taproot.go#L363
     */
    function verifyTaprootLeafCommitment(bytes memory controlBlock, bytes32 witnessProgram, bytes memory script)
        internal
        pure
        returns (bool)
    {
        // 1. Parse control block
        if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
        if ((controlBlock.length - 33) % 32 != 0) {
            revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
        }

        uint8 leafVersionAndParity = uint8(controlBlock[0]);
        uint8 leafVersion = leafVersionAndParity & LEAF_VERSION_MASK; // Mask out parity bit
        uint8 outputKeyParity = leafVersionAndParity & PARITY_MASK;

        bytes32 internalKey;
        assembly {
            internalKey := mload(add(controlBlock, 33)) // Skip length (32) + first byte (1)
        }

        // 2. Compute leaf hash
        bytes32 leafHash = tapLeafHash(leafVersion, script);

        // 3. Compute merkle root by processing the merkle proof
        bytes32 merkleRoot = leafHash;
        uint256 proofLength = (controlBlock.length - 33) >> 5;

        for (uint256 i = 0; i < proofLength; i++) {
            bytes32 proofElement;
            assembly {
                // Read proof element at offset: 32 (length) + 1 (version/parity) + 32 (internalKey) + i*32
                proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
            }
            merkleRoot = tapBranchHash(merkleRoot, proofElement);
        }

        // 4. Compute expected output key P = Q + hash(Q || merkleRoot) * G
        (bytes32 expectedOutputKey, bool computedYIsOdd) = computeOutputKey(internalKey, abi.encodePacked(merkleRoot));

        // 5. Verify witness program matches expected output key (x-coordinate)
        if (witnessProgram != expectedOutputKey) {
            return false;
        }

        // 6. Verify the parity of the y-coordinate matches the control block
        // Per BIP341 and Bitcoin consensus rules
        bool expectedYIsOdd = (outputKeyParity == 1);
        if (computedYIsOdd != expectedYIsOdd) {
            return false;
        }

        return true;
    }

    /**
     * @notice Parse control block into components
     * @param controlBlock The control block bytes
     * @return leafVersion The leaf version (0xC0 for Tapscript v0)
     * @return outputKeyParity The parity bit of the output key
     * @return internalKey The 32-byte internal public key
     * @return merkleProof Array of 32-byte merkle proof hashes
     */
    function parseControlBlock(bytes memory controlBlock)
        internal
        pure
        returns (uint8 leafVersion, uint8 outputKeyParity, bytes32 internalKey, bytes32[] memory merkleProof)
    {
        if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
        if ((controlBlock.length - 33) % 32 != 0) {
            revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
        }

        uint8 leafVersionAndParity = uint8(controlBlock[0]);
        leafVersion = leafVersionAndParity & LEAF_VERSION_MASK;
        outputKeyParity = leafVersionAndParity & PARITY_MASK;

        assembly {
            internalKey := mload(add(controlBlock, 33))
        }

        uint256 proofLength = (controlBlock.length - 33) >> 5;
        merkleProof = new bytes32[](proofLength);

        for (uint256 i = 0; i < proofLength; i++) {
            assembly {
                let proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
                mstore(add(add(merkleProof, 32), mul(i, 32)), proofElement)
            }
        }

        return (leafVersion, outputKeyParity, internalKey, merkleProof);
    }

    /**
     * @notice Build control block from components
     * @param leafVersion The leaf version (0xC0 for Tapscript v0)
     * @param outputKeyParity The parity bit (0 or 1)
     * @param internalKey The internal public key
     * @param merkleProof Array of merkle proof hashes
     * @return The encoded control block
     */
    function buildControlBlock(
        uint8 leafVersion,
        uint8 outputKeyParity,
        bytes32 internalKey,
        bytes32[] memory merkleProof
    ) internal pure returns (bytes memory) {
        uint8 leafVersionAndParity = leafVersion | (outputKeyParity & PARITY_MASK);

        bytes memory controlBlock = abi.encodePacked(leafVersionAndParity, internalKey);

        for (uint256 i = 0; i < merkleProof.length; i++) {
            controlBlock = abi.encodePacked(controlBlock, merkleProof[i]);
        }

        return controlBlock;
    }
}

src/protocol/lib/taproot/TaprootConstants.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title TaprootConstants
 * @notice Constants for BIP341 Taproot verification
 * @dev Provides internal key Q, curve parameters, and BIP340 tagged hash tags
 */
library TaprootConstants {
    // ============ Internal Key Q ============
    // The x-only internal public key (32 bytes) used for all vaults
    // BIP341 recommends using a nothing-up-my-sleeve (NUMS) point to disable keypath spending
    // This is the recommended unspendable key from BIP341:
    // lift_x(0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0)
    bytes32 constant INTERNAL_KEY_Q = 0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0;

    // ============ Secp256k1 Curve Parameters ============
    // Generator point coordinates
    uint256 constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
    uint256 constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;

    // Curve equation: y^2 = x^3 + ax + b
    uint256 constant AA = 0; // a coefficient
    uint256 constant BB = 7; // b coefficient

    // Prime field modulus
    uint256 constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
    uint256 constant PP_S1D2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFE17;

    // Curve order (for scalar operations)
    uint256 constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;

    // ============ BIP340/341/342 Tagged Hash Tags ============
    // BIP340 tag for Taproot tweaking (raw UTF-8 bytes, not padded)
    bytes constant TAG_TAPTWEAK = bytes("TapTweak");

    // BIP341 tag for leaf hashing (raw UTF-8 bytes, not padded)
    bytes constant TAG_TAPLEAF = bytes("TapLeaf");

    // BIP341 tag for branch hashing (raw UTF-8 bytes, not padded)
    bytes constant TAG_TAPBRANCH = bytes("TapBranch");

    // BIP340 tag for signature challenges (for future use)
    bytes constant TAG_TAPBIP0340CHALLENGE = bytes("BIP0340/challenge");

    // ============ Tapscript Constants ============
    // Leaf version for Tapscript v0 (BIP342)
    uint8 constant TAPSCRIPT_LEAF_VERSION = 0xC0;

    // Taproot witness version
    uint8 constant TAPROOT_WITNESS_VERSION = 0x01;

    // Taproot output key size (x-only pubkey)
    uint8 constant TAPROOT_PUBKEY_SIZE = 32;
}

src/protocol/lib/types/BTCVaultRegistryTypes.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

/// @title BTCVaultRegistryTypes
/// @notice Protocol-owned BTC vault registry types used by BTCVaultRegistry and protocol callers
library BTCVaultRegistryTypes {
    /// @notice Vault provider registration data stored by the protocol
    struct VaultProvider {
        bytes32 btcPubKey;
        address applicationEntryPoint;
        uint16 commissionBps;
    }

    /// @notice One versioned operation-BTC-key entry: the x-only key and the registry epoch
    ///         at which it became current. v0 is the registration key (not stored here).
    struct OpBtcKeyVersion {
        bytes32 key;
        uint64 epoch;
    }

    /// @notice One versioned operation-ETH-key entry: the relay/ACK address and its epoch.
    ///         v0 = adminEthAddress (derived, not stored here).
    struct OpEthKeyVersion {
        address key;
        uint64 epoch;
    }

    /// @notice One versioned payout-script entry: the scriptPubKey bytes and its epoch.
    ///         v0 = BIP-86 P2TR of op-key v0 (derived, not stored here); v1 = required registration payout.
    struct PayoutScriptVersion {
        bytes script;
        uint64 epoch;
    }

    /// @notice Protocol-only vault metadata stored alongside the shared basic vault info
    /// @dev Append-only: when adding fields for an upgradeable deployment, add them
    ///      after `claimExpiredUntil` so existing per-vault rows decode unchanged.
    struct BTCVaultProtocolInfo {
        bytes depositorSignedPeginTx;
        uint16 universalChallengersVersion;
        uint16 appVaultKeepersVersion;
        uint16 offchainParamsVersion;
        uint256 verifiedAt;
        bytes32 depositorWotsPkHash;
        bytes32 hashlock;
        uint8 htlcVout;
        bytes depositorPopSignature;
        bytes32 prePeginTxHash;
        uint16 vaultProviderCommissionBps;
        uint256 claimExpiredUntil;
        // RFC 004: appended at the end to preserve storage layout for any future upgrade
        // of an already-deployed BTCVaultRegistry.
        uint16 vaultCoreVersion;
        // per-pegin operation-key epochs the vault bonds against. Appended after
        // `vaultCoreVersion` so existing rows decode unchanged; all three pack into one slot.
        uint64 vpKeyEpoch;
        uint64 appKeeperKeyEpoch;
        uint64 ucKeyEpoch;
    }

    /// @notice ACK submission payload for batch ACK processing
    struct ACKSubmission {
        bytes32 vaultId;
        bytes signature;
    }

    /// @notice Batched pegin request payload for a shared depositor and vault provider
    struct BatchPeginRequest {
        bytes32 depositorBtcPubKey;
        bytes btcPopSignature;
        bytes unsignedPrePeginTx;
        bytes depositorSignedPeginTx;
        bytes32 hashlock;
        uint8 htlcVout;
        uint32 referralCode;
        bytes depositorPayoutBtcAddress;
        bytes32 depositorWotsPkHash;
    }
}

src/protocol/lib/types/Constants.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

library Constants {
    /// @notice Bitcoin dust threshold - minimum value for a standard output (546 satoshis)
    /// @dev Outputs below this threshold are considered "dust" and rejected by Bitcoin network
    uint64 constant BTC_DUST_THRESHOLD = 546;

    /// @notice Maximum byte length for a depositor BTC payout address (scriptPubKey)
    /// @dev Standard scriptPubKey types are at most 34 bytes; 128 bytes provides headroom for future types
    uint256 constant MAX_PAYOUT_ADDRESS_LENGTH = 128;

    /// @notice Minimum vault provider commission in basis points (1 = 0.01%)
    /// @dev Hardcoded floor so off-chain payout construction never handles a zero commission output
    uint16 constant MIN_VP_COMMISSION_BPS = 1;
}

src/protocol/lib/types/Errors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

library Errors {
    // =============================================================================
    //                              COMMON VALIDATION ERRORS
    // =============================================================================

    /// @notice Error thrown when zero address is provided where not allowed
    error ZeroAddress();

    /// @notice Error thrown when caller is not authorized
    error Unauthorized();

    /// @notice Error thrown when invalid amount is provided
    error InvalidAmount();

    /// @notice A circuit version's approved verifier/checkpoint cannot be replaced
    error ProverInfoAlreadyRegistered(uint16 circuitVersion);

    /// @notice Offchain parameter updates require the selected circuit's approved verifier/checkpoint
    error ProverInfoNotRegistered(uint16 circuitVersion);

    /// @notice Error thrown when transfer of funds fails
    error TransferFailed();

    // =============================================================================
    //                              ACCESS CONTROL ERRORS
    // =============================================================================

    /// @notice Error thrown when caller is not the application entry point
    error OnlyApplicationEntryPoint();

    // =============================================================================
    //                              MARKET/VAULT ERRORS
    // =============================================================================

    /// @notice Error thrown when vault is not found or invalid
    error InvalidVault();

    // =============================================================================
    //                              PROVIDER/LIQUIDATOR ERRORS
    // =============================================================================

    /// @notice Error thrown when provider ETH address is already registered
    error EthKeyAlreadyRegistered();

    /// @notice Error thrown when invalid BTC public key is provided
    error InvalidBTCPublicKey();

    /// @notice Error thrown when depositor WOTS public key hash is missing (bytes32(0))
    error InvalidDepositorWotsPkHash();

    /// @notice Error thrown when a depositor reuses a WOTS public key hash across pegin requests
    error DepositorWotsPkHashAlreadyUsed();

    /// @notice Error thrown when BTC Proof of Possession signature is invalid
    error InvalidBTCProofOfPossession();

    /// @notice Error thrown when the operation-ETH-key self proof of possession is invalid
    error InvalidEthProofOfPossession();

    /// @notice Error thrown when a BTC public key is already registered
    error BtcKeyAlreadyRegistered();

    /// @notice Error thrown when incorrect registration fee amount is provided
    error InvalidRegistrationFee();

    /// @notice Error thrown when vault provider commission is below the hardcoded minimum
    /// @param provided The commission provided in basis points
    /// @param minimum The minimum required commission in basis points
    error CommissionBelowMinimum(uint16 provided, uint16 minimum);

    /// @notice Error thrown when vault provider commission exceeds the protocol maximum
    /// @param provided The commission provided in basis points
    /// @param maximum The maximum allowed commission in basis points
    error CommissionAboveMaximum(uint16 provided, uint16 maximum);

    /// @notice Error thrown when vault provider commission update is a no-op
    error CommissionUnchanged();

    /// @notice Error thrown when the live vault provider commission exceeds the
    /// maximum the depositor was willing to accept at peg-in submission time.
    /// @param maxAcceptable The depositor-supplied upper bound in basis points
    /// @param actual The current on-chain VP commission in basis points
    error VaultProviderCommissionExceeded(uint16 maxAcceptable, uint16 actual);

    /// @notice Error thrown when vault provider is not registered
    error VaultProviderNotRegistered();

    // =============================================================================
    //                              APPLICATION ERRORS
    // =============================================================================

    /// @notice Error thrown when application is already registered
    error ApplicationAlreadyRegistered();

    /// @notice Error thrown when application is not registered
    error ApplicationNotRegistered();

    /// @notice Error thrown when application is not in Active status (unregistered or paused)
    error ApplicationNotActive();

    /// @notice Error thrown when application has invalid status for the requested operation
    error InvalidApplicationStatus();

    /// @notice Error thrown when vault keepers array is empty
    error EmptyVaultKeepers();

    // =============================================================================
    //                              PEGIN/PEGOUT ERRORS
    // =============================================================================

    /// @notice Error thrown when invalid transaction data is provided
    error InvalidTransaction();

    /// @notice Error thrown when depositor payout BTC address is empty
    error EmptyPayoutAddress();

    /// @notice Error thrown when depositor payout BTC address exceeds maximum allowed length
    error PayoutAddressTooLong();

    /// @notice Error thrown when vault with same transaction hash already exists
    error VaultAlreadyExists();

    /// @notice Error thrown when vault fee is already escrowed for a vault
    error VaultFeeAlreadyEscrowed();

    /// @notice Error thrown when there are no escrowed fees to distribute or forfeit for a vault
    error NoEscrowedFees();

    /// @notice Error thrown when pegin request not found
    error BTCVaultNotFound();

    /// @notice Error thrown when pegin request has invalid BTC vault status
    error InvalidBTCVaultStatus();

    /// @notice Error thrown when attempting to expire a vault whose timeout has not elapsed
    error PeginNotExpired();

    /// @notice Error thrown when invalid providers or liquidators list
    error InvalidParticipantsList();

    /// @notice Error thrown when a participant list contains duplicate ETH addresses or BTC public keys
    error DuplicateParticipant();

    /// @notice Error thrown when an ETH address or BTC public key appears in multiple participant roles
    error ParticipantRoleOverlap();

    /// @notice Error thrown when caller is not authorized for ACK
    error NotAuthorizedToACK();

    /// @notice Error thrown when vault keeper is not authorized for a protocol operation
    error UnauthorizedVaultKeeper();

    /// @notice Error thrown when a blocklisted vault keeper attempts redemption
    error BlocklistedVaultKeeper();

    /// @notice Error thrown when pegin transaction has expired
    error PeginTransactionExpired();

    /// @notice Error thrown when a pre-pegin output (txHash + vout) is already claimed by another vault
    error PrePeginOutputAlreadyUsed();

    /// @notice Error thrown when a signed pegin transaction is already claimed by another vault
    error PeginTransactionAlreadyUsed();

    /// @notice Error thrown when pegin fee does not match required amount
    error InvalidPeginFee(uint256 provided, uint256 required);

    // =============================================================================
    //                              BTC VERIFICATION ERRORS
    // =============================================================================

    /// @notice Error thrown when amount is below minimum threshold
    error AmountBelowMinimumThreshold(uint256 actual, uint256 minimum);

    /// @notice Error thrown when invalid output index provided
    error InvalidOutputIndex(uint256 provided, uint256 maxValid);

    /// @notice Error thrown when Pre-PegIn transaction has too many HTLC outputs
    error TooManyHtlcOutputs(uint256 outputCount, uint256 maxAllowed);

    /// @notice Error thrown when Pre-PegIn transaction has too many funding inputs
    error TooManyFundingInputs(uint256 inputCount, uint256 maxAllowed);

    /// @notice Error thrown when vault BTC amount is below minimum threshold
    /// @param actual The actual vault amount in satoshis
    /// @param minimum The minimum required amount in satoshis
    error VaultBelowMinimum(uint256 actual, uint256 minimum);

    /// @notice Error thrown when vault BTC amount exceeds maximum threshold
    /// @param actual The actual vault amount in satoshis
    /// @param maximum The maximum allowed amount in satoshis
    error VaultAboveMaximum(uint256 actual, uint256 maximum);

    // =============================================================================
    //                              PARAMS ERRORS
    // =============================================================================

    /// @notice Error thrown when a parameter value of zero is provided where not allowed
    error ZeroValue();

    /// @notice Error thrown when attempting to overwrite an existing version
    error VersionAlreadyExists();

    /// @notice Error thrown when security council configuration is invalid
    error InvalidSecurityCouncilConfig();

    /// @notice Error thrown when no universal challengers are configured
    error NoUniversalChallengersConfigured();

    /// @notice Error thrown when no application vault keepers are configured
    error NoAppVaultKeepersConfigured();

    /// @notice Error thrown when an operation-key version counter would overflow uint16
    error OperationKeyVersionOverflow();

    // =============================================================================
    //                              APPLICATION CAP ERRORS
    // =============================================================================

    /// @notice Error thrown when activating a vault would exceed application BTC caps
    error CapExceeded();

    /// @notice Error thrown when a pegin submission would exceed the global live-vault cap
    error LiveVaultCapExceeded();

    /// @notice Error thrown when the live-vault release delay exceeds its protocol maximum
    /// @param requested The requested release delay in Ethereum blocks
    /// @param maximum The maximum permitted release delay in Ethereum blocks
    error LiveVaultReleaseDelayTooLong(uint256 requested, uint256 maximum);

    /// @notice Error thrown when lowering the live-vault release delay with queued releases
    error LiveVaultReleaseDelayDecreaseBlocked();

    /// @notice Error thrown when a depositor is not allow-listed for a gated application
    error DepositNotAllowed();

    /// @notice Error thrown when setting depositor allowances while the gate is disabled
    error AllowListDisabled();

    /// @notice Error thrown when the destination application declines a batch of pegin requests for
    ///         the given receiver, e.g. because the resulting position would breach the
    ///         application's size boundaries
    error PositionSizesRejectedByApplication();

    /// @notice Error thrown when maxPegInAmount is less than minimumPegInAmount
    /// @param max The configured maximum peg-in amount
    /// @param min The configured minimum peg-in amount
    error MaxPegInBelowMinPegIn(uint256 max, uint256 min);

    /// @notice Error thrown when initial array size exceeds the maximum limit
    /// @param actual The actual array size
    /// @param maximum The maximum size allowed
    error ArrayExceedsMaxSize(uint256 actual, uint256 maximum);

    // =============================================================================
    //                              ATOMIC SWAP ERRORS
    // =============================================================================

    /// @notice Error thrown when `activateVaultWithSecret` would push the application past its BTC cap
    /// @dev Raised when `CapPolicy.incrementUsage` returns false. The vault stays `Verified`; the depositor
    ///      recovers through `activateVaultWithSecretAndRedeem`.
    error ActivationCapExceeded();

    /// @notice Error thrown when hashlock is zero
    error InvalidHashlock();

    /// @notice Error thrown when hashlock is already used by another vault
    error DuplicateHashlock();

    /// @notice Error thrown when SHA256(secret) does not match the hashlock
    error InvalidSecret();

    /// @notice Error thrown when ACK is submitted before all pegin input signatures are posted
    error PeginSignaturesIncomplete();

    /// @notice Error thrown when a pegin input signature is not 64 bytes (Schnorr)
    error InvalidSignatureLength();

    /// @notice Error thrown when a pegin input signature slot has already been written
    error PeginInputSignatureAlreadySubmitted();

    /// @notice Error thrown when atomic swap activation deadline has passed
    error ActivationDeadlineExpired();

    /// @notice Error thrown when the protocol state resolved at submit differs from what the depositor built against
    /// @dev Both values are `PeginLogic._peginFingerprint` outputs: the one the depositor built from
    ///      public state and the one the registry resolves at inclusion. A mismatch means a participant rotated an
    ///      operation key, a roster changed, or the offchain-params / vault-core version moved between
    ///      the moment the depositor resolved that state and the inclusion of `submitPeginRequest`, so
    ///      the Pre-PegIn commits to bytes this vault would not bond to. Reverting keeps the depositor
    ///      from funding a vault every daemon would reject. The seven components each have their own
    ///      public getter, so a caller can diff them to find which axis moved.
    error PeginFingerprintChanged(bytes32 expected, bytes32 actual);

    /// @notice Error thrown when application activation is attempted before the observation window has elapsed
    /// @dev Cutoff: block.number < verifiedAt + peginActivationDelay. Applies to `activateVaultWithSecret` only;
    ///      `activateVaultWithSecretAndRedeem` is unaffected because it mints no vaultBTC.
    error ActivationDelayNotElapsed();

    /// @notice Error thrown when claimExpiredVault is called past the post-expiry grace window
    /// @dev Cutoff: block.number > (block.number at reportExpired) + expiredPegInGraceBlocks
    error PostExpiryGraceWindowElapsed();

    /// @notice Error thrown when the Bitcoin refund window does not safely outlast the Ethereum activation window
    /// @param tRefund The configured Bitcoin refund window in Bitcoin blocks
    /// @param pegInActivationTimeout The configured activation window in Ethereum blocks
    error UnsafePeginTimingConfiguration(uint32 tRefund, uint64 pegInActivationTimeout);

    // =============================================================================
    //                              TIMELOCK VALIDATION ERRORS
    // =============================================================================

    /// @notice Error thrown when initializing the timelock with a delay that exceedes the Standard Governance Delay (5 days)
    error InvalidDelay();

    /// @notice Error thrown when initializing the timelock with short delay arrays of different lengths
    error InvalidShortDelayArrays();
}

src/protocol/lib/types/Events.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

library Events {
    // =============================================================================
    //                              REGISTRATION EVENTS
    // =============================================================================

    /// @notice Event emitted when a vault provider is registered
    /// @param provider The provider address
    /// @param btcPubKey The provider's x-only BTC public key
    /// @param applicationEntryPoint The application this provider is registered for
    /// @param commissionBps The provider's peg-out commission in basis points
    /// @param payoutScriptPubKey The provider's required payout scriptPubKey, stored as payout v1
    event VaultProviderRegistered(
        address indexed provider,
        bytes32 btcPubKey,
        address indexed applicationEntryPoint,
        uint16 commissionBps,
        bytes payoutScriptPubKey
    );

    /// @notice Event emitted when a vault provider updates their commission
    /// @param provider The provider address
    /// @param newCommissionBps The new commission in basis points
    event VaultProviderCommissionUpdated(address indexed provider, uint16 newCommissionBps);

    // =============================================================================
    //                              APPLICATION EVENTS
    // =============================================================================

    /// @notice Event emitted when a vault can be claimed (for ZK proof generation)
    /// @param vaultId The vault identifier
    /// @param peginTxHash The raw Bitcoin peg-in transaction hash
    /// @param claimerPK The BTC public key authorized to claim this vault
    /// @param vaultCoreVersion Vault Core protocol version stamped on this vault at peg-in (RFC 004)
    /// @param proverCircuitVersion Prover circuit version (universal SP1 ELF set) for this vault
    /// @param offchainParamsVersion Version of offchain parameters for this vault
    /// @param universalChallengersVersion Version of universal challengers for this vault
    /// @param appVaultKeepersVersion Version of application vault keepers for this vault
    event VaultClaimableBy(
        bytes32 indexed vaultId,
        bytes32 indexed peginTxHash,
        bytes32 indexed claimerPK,
        uint16 vaultCoreVersion,
        uint16 proverCircuitVersion,
        uint16 offchainParamsVersion,
        uint16 universalChallengersVersion,
        uint16 appVaultKeepersVersion
    );

    /// @notice Event emitted when an ACK is submitted for a pegin request
    event PeginACKSubmitted(bytes32 indexed vaultId, address indexed ackers);

    /// @notice Event emitted when a pegin request is verified
    event PeginRequestVerified(bytes32 indexed vaultId, address indexed depositor);

    /// @notice Event emitted when a pegin request is submitted
    /// @param vaultId The vault identifier derived from peginTxHash + depositor
    /// @param peginTxHash The raw Bitcoin peg-in transaction hash
    /// @param depositor The depositor address
    /// @param vaultProvider The vault provider address
    /// @param amount The amount of BTC in the vault
    /// @param vaultCoreVersion Vault Core protocol version stamped on this vault at peg-in (RFC 004)
    /// @param universalChallengersVersion Version of universal challengers for this vault
    /// @param appVaultKeepersVersion Version of application vault keepers for this vault
    /// @param proverCircuitVersion Version of prover circuit (universal SP1 ELF set) for this vault
    /// @param offchainParamsVersion Version of offchain parameters for this vault
    /// @param referralCode Referral attribution code (0 if unused)
    /// @param depositorPayoutBtcAddress Depositor-specified BTC payout address (scriptPubKey)
    /// @param depositorWotsPkHash keccak256(depositorWotsPublicKey) for VP authentication
    /// @param hashlock The SHA256 hashlock h
    /// @param btcPopSignature Depositor BTC proof of possession (DA only)
    /// @param htlcVout Index of the HTLC output in the Pre-PegIn transaction that this PegIn spends
    /// @param unsignedPrePeginTx The unsigned pre-pegin transaction (DA only)
    /// @param depositorSignedPeginTx The depositor-signed pegin transaction (DA only)
    /// @param vpKeyEpoch VP operation-key epoch the vault bonds against
    /// @param appKeeperKeyEpoch App-keeper operation-key epoch the vault bonds against
    /// @param ucKeyEpoch Universal-challenger operation-key epoch the vault bonds against
    /// @param maxAcceptableCommissionBps Depositor-approved upper bound (inclusive) on the VP's
    ///        commission in basis points, as submitted with the request
    event PegInSubmitted(
        bytes32 indexed vaultId,
        bytes32 indexed peginTxHash,
        address indexed depositor,
        address vaultProvider,
        uint256 amount,
        uint16 vaultCoreVersion,
        uint16 universalChallengersVersion,
        uint16 appVaultKeepersVersion,
        uint16 proverCircuitVersion,
        uint16 offchainParamsVersion,
        uint32 referralCode,
        bytes depositorPayoutBtcAddress,
        bytes32 depositorWotsPkHash,
        bytes32 hashlock,
        bytes btcPopSignature,
        uint8 htlcVout,
        bytes unsignedPrePeginTx,
        bytes depositorSignedPeginTx,
        uint64 vpKeyEpoch,
        uint64 appKeeperKeyEpoch,
        uint64 ucKeyEpoch,
        uint16 maxAcceptableCommissionBps
    );

    /// @notice Non-indexed data payload of `PegInSubmitted`
    /// @dev Member order/types mirror the non-indexed `PegInSubmitted` parameters exactly, so
    ///      `abi.encode` of this struct equals the event's data section.
    struct PegInSubmittedData {
        address vaultProvider;
        uint256 amount;
        uint16 vaultCoreVersion;
        uint16 universalChallengersVersion;
        uint16 appVaultKeepersVersion;
        uint16 proverCircuitVersion;
        uint16 offchainParamsVersion;
        uint32 referralCode;
        bytes depositorPayoutBtcAddress;
        bytes32 depositorWotsPkHash;
        bytes32 hashlock;
        bytes btcPopSignature;
        uint8 htlcVout;
        bytes unsignedPrePeginTx;
        bytes depositorSignedPeginTx;
        uint64 vpKeyEpoch;
        uint64 appKeeperKeyEpoch;
        uint64 ucKeyEpoch;
        uint16 maxAcceptableCommissionBps;
    }

    /// @notice Emit `PegInSubmitted` from its three indexed topics and a non-indexed data struct
    /// @dev Emits via `abi.encode(data)` + `log4` instead of a 19-argument stack tuple (--ir-minimum
    ///      stack); topics and data are byte-identical to a direct `emit PegInSubmitted(...)`.
    /// @param vaultId Indexed topic 1
    /// @param peginTxHash Indexed topic 2
    /// @param depositor Indexed topic 3
    /// @param data The 19 non-indexed event fields
    function emitPegInSubmitted(bytes32 vaultId, bytes32 peginTxHash, address depositor, PegInSubmittedData memory data)
        internal
    {
        bytes memory encoded = abi.encode(data);
        bytes32 topic0 = PegInSubmitted.selector;
        bytes32 depositorTopic = bytes32(uint256(uint160(depositor)));
        // Only reads within the allocated `encoded` array, so the IR pipeline may keep
        // its stack-to-memory escape enabled for enclosing functions (--ir-minimum stack).
        assembly ("memory-safe") {
            // `abi.encode(data)` lays out [len][offset=0x20][tuple...]; the event data section is the
            // inline tuple, which starts at encoded+0x40 and has length len-0x20.
            let len := mload(encoded)
            log4(add(encoded, 0x40), sub(len, 0x20), topic0, vaultId, peginTxHash, depositorTopic)
        }
    }

    /// @notice Event emitted when a vault is activated via secret reveal
    /// @param vaultId The vault identifier
    /// @param depositor The depositor address
    /// @param secret The 32-byte preimage satisfying SHA256(secret) == hashlock
    event PeginActivated(bytes32 indexed vaultId, address indexed depositor, bytes32 secret);

    /// @notice Event emitted when an `Expired` vault is redeemed via `claimExpiredVault`
    /// @dev Off-chain workers consume this event to extract the preimage and construct the
    ///      BTC-side Claim transaction, mirroring how `PeginActivated` exposes the secret on
    ///      the standard activation path. Emitted before the two `VaultClaimableBy` events so
    ///      consumers can stage state before the authorization signal.
    /// @param vaultId The vault identifier
    /// @param depositor The depositor address recorded at submission time
    /// @param secret The 32-byte preimage satisfying SHA256(secret) == hashlock
    event ExpiredVaultClaimed(bytes32 indexed vaultId, address indexed depositor, bytes32 secret);

    /// @notice Event emitted when a pegin input signature is posted for a specific BTC public key
    /// @param vaultId The vault identifier
    /// @param btcPubKey The BTC public key this signature is bound to
    /// @param submitter The party that submitted the signature candidate
    /// @param signature The pegin input signature bytes
    event PeginInputSignaturePosted(
        bytes32 indexed vaultId, bytes32 indexed btcPubKey, address indexed submitter, bytes signature
    );

    /// @notice Event emitted when the vault provider posts a pegin input signature batch
    /// @param vaultId The vault identifier
    /// @param vaultProvider The vault provider who submitted the batch
    event PeginInputSignaturesBatchPosted(bytes32 indexed vaultId, address indexed vaultProvider);

    /// @notice Reason why a pegin was expired
    enum ExpirationReason {
        AckTimeout,
        ActivationTimeout
    }

    /// @notice Event emitted when a pegin transaction has expired
    event PeginExpired(
        bytes32 indexed vaultId, address indexed depositor, address indexed vaultProvider, ExpirationReason reason
    );
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    ":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":aave-v4/=lib/aave-v4/src/",
    ":elliptic-curve-solidity/=lib/elliptic-curve-solidity/",
    ":erc4626-tests/=lib/aave-v4/lib/erc4626-tests/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    ":src/access/=lib/aave-v4/src/access/",
    ":src/config-engine/=lib/aave-v4/src/config-engine/",
    ":src/dependencies/=lib/aave-v4/src/dependencies/",
    ":src/deployments/=lib/aave-v4/src/deployments/",
    ":src/hub/=lib/aave-v4/src/hub/",
    ":src/interfaces/IExtSload.sol=lib/aave-v4/src/interfaces/IExtSload.sol",
    ":src/interfaces/IIntentConsumer.sol=lib/aave-v4/src/interfaces/IIntentConsumer.sol",
    ":src/interfaces/IMulticall.sol=lib/aave-v4/src/interfaces/IMulticall.sol",
    ":src/interfaces/INoncesKeyed.sol=lib/aave-v4/src/interfaces/INoncesKeyed.sol",
    ":src/interfaces/IRescuable.sol=lib/aave-v4/src/interfaces/IRescuable.sol",
    ":src/libraries/=lib/aave-v4/src/libraries/",
    ":src/position-manager/=lib/aave-v4/src/position-manager/",
    ":src/spoke/=lib/aave-v4/src/spoke/",
    ":src/utils/=lib/aave-v4/src/utils/",
    ":vault-contracts/=src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.