Skip to content
Verified contractPartialLicenseRef-DCL-1.0

MigrationRegistry

Address0x172e587adcf5cadd70b2b13f720171a9f5bec591
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.25

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 100,000 runs
EVM version
cancun
License
LicenseRef-DCL-1.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,286,410
Creation transaction
0xb811fdfa52…a6aac0c717

src/concrete/MigrationRegistry.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity =0.8.25;

import {IMigrationRegistryV4, Prerequisite, MIGRATION_HEAD_GENESIS} from "../interface/IMigrationRegistryV4.sol";
import {RegistryDelegates} from "../abstract/RegistryDelegates.sol";
import {LibIMetaBoardV1_2} from "rain-metadata-0.1.43/src/lib/LibIMetaBoardV1_2.sol";

/// @dev One line's record of one migration. Written in one call, so a record
/// can never hold one half of itself.
struct MigrationRecord {
    /// The moment recorded against the migration. Zero means never applied,
    /// which no write records.
    uint256 appliedAt;
    /// The list the write gave, as given: the head it was applied onto in
    /// the line, then the prerequisites. Empty only for a migration never
    /// applied.
    Prerequisite[] appliedAfter;
    /// The account that made the write: the writer or a delegate it approved.
    /// Zero only for a migration never applied.
    address writtenBy;
}

/// @title MigrationRegistry
/// @notice The whole of `IMigrationRegistryV4`: a write applies one migration
/// into `writer`'s line, by `writer` or a delegate it approved, in a namespace
/// it names, after one list — the head it believes that line is at, then the
/// migrations in any line it names — at the moment it says the migration ran,
/// and anyone reads when a given writer's line in a given namespace applied a
/// given migration, what it applied it onto, what it applied it after, which
/// account wrote it, or where that line has got to.
///
/// There is deliberately nothing else. No removal, no upgrade, no pause, and no
/// authority but each writer's over its own lines — the reason nothing here is
/// CONFIGURED at compile time. `MIGRATION_HEAD_GENESIS` is a compile-time
/// constant, but it is the same value for every consumer on every chain and
/// names nobody, so it is part of what this contract IS rather than a choice
/// welded into it.
///
/// A root would have to be welded into the creation code so it cannot be
/// rotated, which puts it in the deterministic address. The account that
/// applies a migration is a different Safe, deployer or timelock for every
/// consumer and every chain, so one root would have to be all of them at once,
/// and baking each consumer's authority into the creation code would give each
/// a different address for what is meant to be one shared registry.
///
/// Keying by the writer removes the authority instead of choosing one. Anyone
/// may write, but only under themselves or a writer that approved them, so a
/// reader asking about the lines of an authority it already trusts is reading
/// something only that authority or its delegates could have written. Every
/// other writer's lines hold unforgeable claims that no reader asks about.
/// The namespace under the writer is the writer's to name: one key writes for
/// several repos, and each keeps its own line. With nothing to configure there
/// is also no rollout state in which this contract is inert: it does its whole
/// job the moment it exists on a chain.
///
/// A writer may approve delegates to write one of its lines (`approveV4`), so
/// several executors share one line. The line is still the writer's: only it
/// approves, and the approval lets a delegate write no other line.
///
/// A record is append-only per line, and a head only ever moves forward onto
/// something new. Both writes refuse a migration already applied in the line,
/// which is what makes re-running a migration fail rather than repeat, and
/// refuse one applied onto anything but the line's current head, which is
/// what makes a skipped or out-of-order migration fail rather than diverge.
/// There is no way to unrecord one, and no way to rewrite one — a record
/// describes something that happened, and nothing that happened stops having
/// happened.
///
/// The moment is the CALLER's on `applyMigrationHistoryV4`, so a migration that
/// ran before this contract reached the chain is recordable with the time it
/// actually ran. The order is not the caller's: each record keeps the head it
/// was applied onto, so a line's records are a chain from `headV4` back to
/// `MIGRATION_HEAD_GENESIS` whatever moments they carry. The moments run with
/// that chain rather than against it — a record is never earlier than the one
/// it was applied onto, though it may be equal to it.
///
/// Both writes take one list: the head under the writer in its namespace
/// first, then a record in any other line that must already exist, and refuse
/// the write naming the first of those that does not. The list is the record,
/// so everything a record was applied after is read back exactly as it was
/// written.
///
/// No storage mapping is `public`. `appliedV4`, `appliedOntoV4`,
/// `appliedAfterV4`, `appliedByV4` and `headV4` refuse the zero writer and the
/// zero namespace, `approvedV4` refuses those and the zero delegate, the four
/// record readers refuse the two ids a migration can never be, and a public
/// mapping's generated getter would answer all of them with zero — which for a
/// record is "not applied" and for `headV4` is a value no head can ever hold,
/// i.e. exactly the silent wrong-branch this contract reverts to prevent.
contract MigrationRegistry is IMigrationRegistryV4, RegistryDelegates {
    /// Every record, keyed by writer, namespace and migration. A zero
    /// `appliedAt` means never applied. Not `public`: the only external readers are
    /// `appliedV4`, `appliedOntoV4`, `appliedAfterV4` and `appliedByV4`, which
    /// refuse the inputs that can only be mistakes.
    mapping(address writer => mapping(bytes32 namespace => mapping(bytes32 migration => MigrationRecord record)))
        internal sRecords;

    /// The most recent migration applied in each line. Zero means the line is
    /// empty, which reads out as `MIGRATION_HEAD_GENESIS` — the only place
    /// that translation happens is `headV4`, so no reader and no writer can
    /// disagree about where an empty line is. Not `public`, for the same
    /// reason as the records: the untranslated zero is not a head.
    mapping(address writer => mapping(bytes32 namespace => bytes32 head)) internal sHead;

    /// @inheritdoc IMigrationRegistryV4
    /// @dev The block is the moment, so a caller that has nothing to say about
    /// when its migration ran does not have to say it.
    // slither-disable-next-line timestamp
    // forge-lint: disable-next-line(block-timestamp)
    function applyMigrationV4(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        Prerequisite[] calldata prerequisites,
        bytes calldata meta
    ) external {
        applyMigrationRecord(writer, namespace, migration, block.timestamp, prerequisites, meta);
    }

    /// @inheritdoc IMigrationRegistryV4
    function applyMigrationHistoryV4(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        uint256 appliedAt,
        Prerequisite[] calldata prerequisites,
        bytes calldata meta
    ) external {
        applyMigrationRecord(writer, namespace, migration, appliedAt, prerequisites, meta);
    }

    /// A line is keyed by a writer and a namespace, neither zero.
    function checkScope(address account, bytes32 scope) internal pure override {
        checkLineKey(account, scope);
    }

    /// The zero writer is refused first: nothing can call as it or be approved
    /// by it.
    function checkAccount(address account) internal pure override {
        checkWriter(account);
    }

    /// Reached by every write, so both share one refusal order.
    /// @param writer The line's writer: the caller, or one that approved it.
    /// @param namespace The line under the writer to apply in.
    /// @param migration The migration to apply.
    /// @param appliedAt The moment to record against it.
    /// @param prerequisites The head, then the records that must exist for it
    /// to be written.
    /// @param meta Rain metadata about the record, emitted when non-empty.
    function applyMigrationRecord(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        uint256 appliedAt,
        Prerequisite[] calldata prerequisites,
        bytes calldata meta
    ) internal {
        checkWrite(writer, namespace);
        checkMigrationArguments(namespace, migration, appliedAt);
        checkPrerequisites(writer, namespace, prerequisites);
        writeMigrationRecord(writer, namespace, migration, appliedAt, prerequisites);
        if (meta.length > 0) {
            LibIMetaBoardV1_2.emitMeta(keccak256(abi.encode(writer, namespace, migration)), meta);
        }
    }

    /// The whole list, in order. The first entry is the writer's head, which
    /// may be genesis, checked against the line. Every later entry is a
    /// record key in another line: refused as `appliedV4` refuses the same key,
    /// refused if it is the writer's own line, and then, in a second pass so
    /// no record is read until every entry has been checked, refused if nobody
    /// has written it.
    /// @param writer The line's writer.
    /// @param namespace The line under the writer being written.
    /// @param prerequisites The head, then the records that must exist.
    function checkPrerequisites(address writer, bytes32 namespace, Prerequisite[] calldata prerequisites)
        internal
        view
    {
        // The first entry is the writer at the head the caller believes it is
        // at. An empty list names no head at all, so it is refused as a zero head,
        // which no line can be at; a first entry under anyone but the writer,
        // or in any namespace but the one being written, is not this line's
        // head whatever migration it names.
        bytes32 actualHead = headV4(writer, namespace);
        if (
            prerequisites.length == 0 || prerequisites[0].writer != writer || prerequisites[0].namespace != namespace
                || prerequisites[0].migration != actualHead
        ) {
            revert UnexpectedMigrationHead(
                writer,
                namespace,
                prerequisites.length == 0 ? address(0) : prerequisites[0].writer,
                prerequisites.length == 0 ? bytes32(0) : prerequisites[0].namespace,
                prerequisites.length == 0 ? bytes32(0) : prerequisites[0].migration,
                actualHead
            );
        }
        for (uint256 i = 1; i < prerequisites.length; i++) {
            checkRecordKey(prerequisites[i].writer, prerequisites[i].namespace, prerequisites[i].migration);
            if (prerequisites[i].writer == writer && prerequisites[i].namespace == namespace) {
                revert OwnPrerequisite(prerequisites[i].migration);
            }
        }
        // Zero is the one moment no write records, so equality is the exact
        // test for an absent record; slither reads it as a timestamp compare.
        // slither-disable-start timestamp
        for (uint256 i = 1; i < prerequisites.length; i++) {
            // slither-disable-next-line incorrect-equality
            if (
                sRecords[prerequisites[i].writer][prerequisites[i].namespace][prerequisites[i].migration].appliedAt == 0
            ) {
                revert PrerequisiteNotApplied(
                    prerequisites[i].writer, prerequisites[i].namespace, prerequisites[i].migration
                );
            }
        }
        // slither-disable-end timestamp
    }

    /// The refusals that describe the call alone: the zero namespace, the two
    /// ids a migration can never be, and the one moment a record can never
    /// carry. Reached by every write straight after the caller is checked,
    /// so a malformed argument is reported before a prerequisite or the line
    /// is read.
    /// @param namespace The line under `writer` to apply in.
    /// @param migration The migration to apply.
    /// @param appliedAt The moment to record against it.
    function checkMigrationArguments(bytes32 namespace, bytes32 migration, uint256 appliedAt) internal pure {
        if (namespace == bytes32(0)) {
            revert ZeroNamespace();
        }
        if (migration == bytes32(0)) {
            revert ZeroMigration();
        }
        if (migration == MIGRATION_HEAD_GENESIS) {
            revert GenesisMigration();
        }
        // Zero is the only value refused, so no clock nudge crosses it.
        // slither-disable-start timestamp
        // slither-disable-next-line incorrect-equality
        if (appliedAt == 0) {
            revert ZeroTimestamp();
        }
        // slither-disable-end timestamp
    }

    /// The refusals that describe the line the call arrives at and the block
    /// it lands in, then the record, then `Migrated`. Reached by every write
    /// after `checkMigrationArguments` and `checkPrerequisites`, so there is
    /// one record and one set of refusals whichever entry point supplied the
    /// moment.
    ///
    /// The refusals run from the one that describes the line, to the one
    /// that describes the record at its head, to the one that describes the
    /// block — which is the order in which a caller can do something about
    /// them.
    /// @param writer The line's writer, which `checkWrite` has already
    /// refused as zero.
    /// @param namespace The line under `writer` to apply in.
    /// @param migration The migration to apply.
    /// @param appliedAt The moment to record against it.
    /// @param prerequisites The head the caller believes `writer`'s line is at,
    /// then the records it was applied after, every one of which
    /// `checkPrerequisites` has found to exist.
    function writeMigrationRecord(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        uint256 appliedAt,
        Prerequisite[] calldata prerequisites
    ) internal {
        MigrationRecord storage record = sRecords[writer][namespace][migration];
        if (record.appliedAt != 0) {
            revert MigrationAlreadyApplied(writer, namespace, migration);
        }
        bytes32 actualHead = prerequisites[0].migration;
        // Genesis is never applied, so its record reads zero and this passes.
        uint256 headAppliedAt = sRecords[writer][namespace][actualHead].appliedAt;
        if (appliedAt < headAppliedAt) {
            revert TimestampBeforeHead(appliedAt, headAppliedAt);
        }
        // A forward clock nudge only admits a migration that ran either way.
        // slither-disable-start timestamp
        // forge-lint: disable-next-line(block-timestamp)
        if (appliedAt > block.timestamp) {
            revert FutureTimestamp(appliedAt, block.timestamp);
        }
        // slither-disable-end timestamp
        record.appliedAt = appliedAt;
        record.writtenBy = msg.sender;
        // Pushed one at a time: solc does not copy a calldata array of structs
        // into storage. The record was empty, so this is the whole list.
        for (uint256 i = 0; i < prerequisites.length; i++) {
            record.appliedAfter.push(prerequisites[i]);
        }
        sHead[writer][namespace] = migration;
        emit Migrated(msg.sender, writer, namespace, migration, appliedAt);
    }

    /// @inheritdoc IMigrationRegistryV4
    /// @dev All four refusals are about a caller that has not supplied what it
    /// thinks it has. None can ever be a real record: nothing originates from
    /// the zero address, no write names the zero namespace, and neither write
    /// records the zero id or the genesis one — so answering zero for any of
    /// them would be answering a question the caller did not mean to ask, and
    /// answering it with the value that sends it down its pre-migration
    /// branch.
    function appliedV4(address writer, bytes32 namespace, bytes32 migration) external view returns (uint256) {
        checkRecordKey(writer, namespace, migration);
        return sRecords[writer][namespace][migration].appliedAt;
    }

    /// @inheritdoc IMigrationRegistryV4
    /// @dev The same four refusals as `appliedV4`, for the same reason and on
    /// the same key: a zero answer here reads as "never applied" exactly as a
    /// zero moment does. The head is the first entry of the stored list, and
    /// the list is empty exactly when the record is.
    function appliedOntoV4(address writer, bytes32 namespace, bytes32 migration) external view returns (bytes32) {
        checkRecordKey(writer, namespace, migration);
        Prerequisite[] storage appliedAfterList = sRecords[writer][namespace][migration].appliedAfter;
        return appliedAfterList.length == 0 ? bytes32(0) : appliedAfterList[0].migration;
    }

    /// @inheritdoc IMigrationRegistryV4
    /// @dev The same four refusals again: an empty answer for a key that can
    /// never hold a record would read as "never applied" about a record the
    /// caller did not mean to ask for.
    function appliedAfterV4(address writer, bytes32 namespace, bytes32 migration)
        external
        view
        returns (Prerequisite[] memory)
    {
        checkRecordKey(writer, namespace, migration);
        return sRecords[writer][namespace][migration].appliedAfter;
    }

    /// @inheritdoc IMigrationRegistryV4
    /// @dev The same four refusals as `appliedV4`: a zero answer here reads as
    /// "never applied" exactly as a zero moment does.
    function appliedByV4(address writer, bytes32 namespace, bytes32 migration) external view returns (address) {
        checkRecordKey(writer, namespace, migration);
        return sRecords[writer][namespace][migration].writtenBy;
    }

    /// Refuses the zero writer. The one copy of that refusal, reached by
    /// `checkLineKey` and by `checkWrite`, which must refuse it before
    /// `NotApproved` and before the namespace.
    /// @param writer The line's writer.
    function checkWriter(address writer) internal pure {
        if (writer == address(0)) {
            revert ZeroWriter();
        }
    }

    /// Refuses the zero writer, then the zero namespace: neither names a line.
    /// One function, so every key naming a line refuses the same two things in
    /// the same order.
    /// @param writer The line's writer.
    /// @param namespace The line under the writer.
    function checkLineKey(address writer, bytes32 namespace) internal pure {
        checkWriter(writer);
        if (namespace == bytes32(0)) {
            revert ZeroNamespace();
        }
    }

    /// Refuses the four inputs that can only be a mistake in the caller rather
    /// than a record to read. One function, so the four readers of a record
    /// and the check on every entry after the head cannot drift into refusing
    /// different things.
    /// @param writer The writer being read.
    /// @param namespace The line under the writer being read.
    /// @param migration The migration being asked about.
    function checkRecordKey(address writer, bytes32 namespace, bytes32 migration) internal pure {
        checkLineKey(writer, namespace);
        if (migration == bytes32(0)) {
            revert ZeroMigration();
        }
        if (migration == MIGRATION_HEAD_GENESIS) {
            revert GenesisMigration();
        }
    }

    /// @inheritdoc IMigrationRegistryV4
    /// @dev The zero writer and the zero namespace are refused rather than
    /// answered `genesis`: every line under the zero writer is provably empty
    /// forever, and the zero namespace is a constant nobody set, so "a line
    /// nothing has been applied to" is a true statement about either and a
    /// false one about what the caller meant to ask, which would send a first
    /// migration at it.
    ///
    /// The empty-line zero is translated to genesis here and nowhere else,
    /// which is why this is one `public` function rather than a reader beside an
    /// internal helper: a write compares against exactly what a caller reads, so
    /// the two cannot drift into different ideas of where a line that has
    /// applied nothing is.
    ///
    /// A write reaches it as `headV4(writer, namespace)`, whose writer is never
    /// the zero address (`checkWrite` refuses it) and whose namespace
    /// `checkMigrationArguments` has already refused as zero, so both refusals
    /// are redundant on that path.
    /// It is one function, so it is one pair of refusals, and the reachable
    /// path is the one they are there for.
    function headV4(address writer, bytes32 namespace) public view returns (bytes32) {
        checkLineKey(writer, namespace);
        bytes32 storedHead = sHead[writer][namespace];
        return storedHead == bytes32(0) ? MIGRATION_HEAD_GENESIS : storedHead;
    }
}

dependencies/rain-metadata-0.1.43/src/interface/deprecated/IMetaV1.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.19;

/// Thrown when hashed metadata does NOT match the expected hash.
/// @param expectedHash The hash expected by the `IMetaV1` contract.
/// @param actualHash The hash of the metadata seen by the `IMetaV1` contract.
error UnexpectedMetaHash(bytes32 expectedHash, bytes32 actualHash);

/// Thrown when some bytes are expected to be rain meta and are not.
/// @param unmeta the bytes that are not meta.
error NotRainMetaV1(bytes unmeta);

/// @dev Randomly generated magic number with first bytes oned out.
/// https://github.com/rainprotocol/specs/blob/main/metadata-v1.md
uint64 constant META_MAGIC_NUMBER_V1 = 0xff0a89c674ee7874;

/// @title IMetaV1
interface IMetaV1 {
    /// An onchain wrapper to carry arbitrary Rain metadata. Assigns the sender
    /// to the metadata so that tooling can easily drop/ignore data from unknown
    /// sources. As metadata is about something, the subject MUST be provided.
    /// @param sender The msg.sender.
    /// @param subject The entity that the metadata is about. MAY be the address
    /// of the emitting contract (as `uint256`) OR anything else. The
    /// interpretation of the subject is context specific, so will often be a
    /// hash of some data/thing that this metadata is about.
    /// @param meta Rain metadata V1 compliant metadata bytes.
    /// https://github.com/rainprotocol/specs/blob/main/metadata-v1.md
    //slither-disable-next-line unindexed-event-address
    event MetaV1(address sender, uint256 subject, bytes meta);
}

dependencies/rain-metadata-0.1.43/src/interface/unstable/IMetaV1_2.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.19;

//forge-lint: disable-next-line(unused-import)
import {UnexpectedMetaHash, NotRainMetaV1, META_MAGIC_NUMBER_V1} from "../deprecated/IMetaV1.sol";

/// @title IMetaV1_2
/// Identical to `IMetaV1` but with the subject as a `bytes32` instead of a
/// `uint256`.
//slither-disable-next-line naming-convention
interface IMetaV1_2 {
    /// An onchain wrapper to carry arbitrary Rain metadata. Assigns the sender
    /// to the metadata so that tooling can easily drop/ignore data from unknown
    /// sources. As metadata is about something, the subject MUST be provided.
    /// @param sender The msg.sender.
    /// @param subject The entity that the metadata is about. MAY be the address
    /// of the emitting contract (as `bytes32`) OR anything else. The
    /// interpretation of the subject is context specific, so will often be a
    /// hash of some data/thing that this metadata is about.
    /// @param meta Rain metadata V1 compliant metadata bytes.
    /// https://github.com/rainprotocol/specs/blob/main/metadata-v1.md
    //slither-disable-next-line naming-convention,unindexed-event-address
    event MetaV1_2(address sender, bytes32 subject, bytes meta);
}

dependencies/rain-metadata-0.1.43/src/lib/LibIMetaBoardV1_2.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
//
// Qualified access to another contract's event (`emit IMetaV1_2.MetaV1_2`) is
// a Solidity 0.8.21 language feature, and a library cannot inherit the
// interface to bring the event into scope any other way. That sets the floor
// here, above the `^0.8.19` the rest of the interfaces and libraries carry.
pragma solidity ^0.8.21;

import {IMetaV1_2} from "../interface/unstable/IMetaV1_2.sol";
import {LibMeta} from "./LibMeta.sol";

/// @title LibIMetaBoardV1_2
/// @notice The whole of an `IMetaBoardV1_2` metaboard as internal library
/// logic, so a concrete metaboard is nothing but one delegation per entry
/// point (rainlanguage/rain.metadata#144). The validation and the event live
/// here, unit tested here, and the shipped `MetaBoard` adds no behaviour of
/// its own — the equivalence suite holds its entry point to exactly this.
///
/// `msg.sender` is read INSIDE this library and the internal functions execute
/// in the calling contract's own call context, so the `MetaV1_2` event is
/// emitted BY the metaboard the library is inlined into and attributed TO
/// whoever called it. A delegating concrete cannot get either wrong, and any
/// other contract that wants to be a metaboard gets the same behaviour by
/// inlining the same code rather than by reimplementing it.
library LibIMetaBoardV1_2 {
    /// The whole of `IMetaBoardV1_2.emitMeta`: reject anything that is not
    /// rain metadata, then emit it verbatim under the caller and subject.
    ///
    /// The check is `checkMetaUnhashedV1` because a metaboard is an open
    /// bulletin board with no expected hash to check against — anons MAY send
    /// garbage that happens to carry the magic number, and per `IMetaBoardV1_2`
    /// it is tooling's job to discard suspect data. The magic number is the
    /// only thing a metaboard promises to enforce.
    /// @param subject As per the `MetaV1_2` event.
    /// @param meta As per the `MetaV1_2` event. MUST be prefixed with the rain
    /// metadata magic number or this reverts `NotRainMetaV1`.
    function emitMeta(bytes32 subject, bytes memory meta) internal {
        LibMeta.checkMetaUnhashedV1(meta);
        emit IMetaV1_2.MetaV1_2(msg.sender, subject, meta);
    }
}

dependencies/rain-metadata-0.1.43/src/lib/LibMeta.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.19;

//forge-lint: disable-next-line(unused-import)
import {IMetaV1_2, UnexpectedMetaHash, NotRainMetaV1, META_MAGIC_NUMBER_V1} from "../interface/unstable/IMetaV1_2.sol";

/// @title LibMeta
/// @notice Need a place to put data that can be handled offchain like ABIs that
/// IS NOT etherscan.
library LibMeta {
    /// Returns true if the metadata bytes are prefixed by the Rain meta magic
    /// number. DOES NOT attempt to validate the body of the metadata as offchain
    /// tooling will be required for this.
    /// @param meta The data that may be rain metadata.
    /// @return True if `meta` is metadata, false otherwise.
    function isRainMetaV1(bytes memory meta) internal pure returns (bool) {
        if (meta.length < 8) return false;
        uint256 mask = type(uint64).max;
        uint256 magicNumber = META_MAGIC_NUMBER_V1;
        assembly ("memory-safe") {
            magicNumber := and(mload(add(meta, 8)), mask)
        }
        return magicNumber == META_MAGIC_NUMBER_V1;
    }

    /// Reverts if the provided `meta` is NOT metadata according to
    /// `isRainMetaV1`.
    /// @param meta The metadata bytes to check.
    function checkMetaUnhashedV1(bytes memory meta) internal pure {
        if (!isRainMetaV1(meta)) {
            revert NotRainMetaV1(meta);
        }
    }

    /// Reverts if the provided `meta` is NOT metadata according to
    /// `isRainMetaV1` OR it does not match the expected hash of its data.
    /// @param meta The metadata to check.
    function checkMetaHashedV1(bytes32 expectedHash, bytes memory meta) internal pure {
        bytes32 actualHash;
        assembly ("memory-safe") {
            actualHash := keccak256(add(meta, 0x20), mload(meta))
        }
        if (expectedHash != actualHash) {
            revert UnexpectedMetaHash(expectedHash, actualHash);
        }
        checkMetaUnhashedV1(meta);
    }
}

src/abstract/RegistryDelegates.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.25;

import {IRegistryDelegatesV2} from "../interface/IRegistryDelegatesV2.sol";

/// @title RegistryDelegates
/// @notice The delegation `ConfigRegistry` and `MigrationRegistry` share, as
/// `IRegistryDelegatesV2` describes it. Each registry checks its own other keys
/// before calling in.
abstract contract RegistryDelegates is IRegistryDelegatesV2 {
    mapping(address account => mapping(bytes32 scope => mapping(address delegate => bool))) internal sApproved;

    /// Refuses the zero delegate with `ZeroDelegate`.
    /// @param delegate The delegate.
    function checkDelegateKey(address delegate) internal pure {
        if (delegate == address(0)) {
            revert ZeroDelegate();
        }
    }

    /// Refuses an account this registry does not key. Nothing by default; a
    /// registry that keys fewer overrides it.
    /// @param account The account.
    function checkAccount(address account) internal pure virtual {}

    /// Reached by every write: refuses an account this registry does not key,
    /// then reverts `NotApproved` unless the caller is `account` or a delegate
    /// it approved within `scope`. Settled before anything about the write.
    /// @param account The account written under.
    /// @param scope The scope under `account`.
    function checkWrite(address account, bytes32 scope) internal view {
        checkAccount(account);
        if (msg.sender != account && !sApproved[account][scope][msg.sender]) {
            revert NotApproved(account, scope, msg.sender);
        }
    }

    /// Refuses an account and scope this registry does not key. Nothing by
    /// default; a registry that keys fewer overrides it.
    /// @param account The account.
    /// @param scope The scope under it.
    function checkScope(address account, bytes32 scope) internal pure virtual {}

    /// @inheritdoc IRegistryDelegatesV2
    function approveV4(bytes32 scope, address delegate) external {
        checkScope(msg.sender, scope);
        checkDelegateKey(delegate);
        sApproved[msg.sender][scope][delegate] = true;
        emit Approved(msg.sender, scope, delegate);
    }

    /// @inheritdoc IRegistryDelegatesV2
    function revokeV4(bytes32 scope, address delegate) external {
        checkScope(msg.sender, scope);
        checkDelegateKey(delegate);
        sApproved[msg.sender][scope][delegate] = false;
        emit Revoked(msg.sender, scope, delegate);
    }

    /// @inheritdoc IRegistryDelegatesV2
    function approvedV4(address account, bytes32 scope, address delegate) external view returns (bool) {
        checkScope(account, scope);
        checkDelegateKey(delegate);
        return sApproved[account][scope][delegate];
    }
}

src/interface/IMigrationRegistryV4.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.25;

import {IRegistryDelegatesV2} from "./IRegistryDelegatesV2.sol";
import {IMetaV1_2} from "rain-metadata-0.1.43/src/interface/unstable/IMetaV1_2.sol";

/// @dev The head of a line that has never applied a migration. The first
/// migration applied in a line names this, and every later one names the
/// migration before it.
///
/// It is deliberately NOT zero. Zero is what an uninitialised `bytes32` constant
/// reads as, and a genesis of zero would make an uninitialised predecessor
/// constant a SUCCESSFUL first application on any line that happens to be
/// empty — which is the state of every line on every chain the consumer has
/// not migrated yet, i.e. exactly where a mis-set constant is most likely and
/// most expensive. Under a nonzero genesis that same constant is a revert in
/// every line state, empty or not, for the same reason `ZeroMigration`,
/// `ZeroWriter` and `ZeroNamespace` exist: an uninitialised value is a mistake
/// to be reported, never a question to be answered.
///
/// It is one shared value rather than anything derived per writer, per
/// namespace or per consumer, so it configures nothing and cannot fragment the
/// implementation's deterministic address.
///
/// It is not a migration, and an implementation MUST refuse it as one. A head
/// holds exactly two kinds of value: an applied migration, or this. Letting a
/// migration BE this would put a line that has applied something at a head
/// indistinguishable from one that has applied nothing, which is the same
/// collapse of two distinct facts into one value that `ZeroMigration` exists to
/// refuse — the two values a head can hold that are not migrations are exactly
/// the two values a migration id may not be.
bytes32 constant MIGRATION_HEAD_GENESIS = keccak256("rain.migration-registry.head.genesis");

/// @dev One entry in the list a record was applied after. A write takes the
/// list and `appliedAfterV4` answers it, and they are the same list: the first
/// entry is the head the record is applied onto, under the writer in the
/// namespace it is writing, and every later entry is a record in some other
/// line the write waited on. A later entry is the key `appliedV4` takes, so
/// anything `appliedV4` refuses to answer about is refused as a prerequisite.
struct Prerequisite {
    /// The writer. Never the zero address; in the first entry, the write's
    /// `writer`, whoever calls: a delegate names the writer that approved it.
    address writer;
    /// The namespace under the writer. Never zero; in the first entry, the
    /// namespace the write names.
    bytes32 namespace;
    /// The migration under them. In the first entry, the head the record is
    /// applied onto, which is `MIGRATION_HEAD_GENESIS` for the first migration
    /// in a line. In every later entry, one that must have been applied:
    /// never zero, never `MIGRATION_HEAD_GENESIS`.
    bytes32 migration;
}

/// @title IMigrationRegistryV4
/// @notice A record of which migrations have been applied, when and after
/// what, keyed by writer, namespace and migration. A write names the writer
/// whose line it writes, and that writer, or an account it has approved for
/// the namespace, applies a migration in the line after one list — the head
/// it believes that line is at, then the migrations in any line it waits on —
/// either as applied now (`applyMigrationV4`) or as already applied at a
/// moment it supplies (`applyMigrationHistoryV4`). Anyone reads when a given
/// writer's line in a given namespace applied a given migration (`appliedV4`),
/// what it applied it onto (`appliedOntoV4`), what it applied it after
/// (`appliedAfterV4`), which account wrote the record (`appliedByV4`), and
/// where a given writer's line in a given namespace currently is (`headV4`).
/// A writer approves and revokes delegates per namespace (`approveV4`,
/// `revokeV4`), and anyone reads an approval (`approvedV4`). There is no
/// removal, no upgrade and no authority beyond the writer over its own lines,
/// and an implementation MUST NOT add any.
///
/// The two writes differ only in where the recorded moment comes from.
/// `applyMigrationV4` records the block it lands in, for a script applying its
/// own migration in the same atomic unit as the migration.
/// `applyMigrationHistoryV4` takes the moment as an argument, for a migration
/// that already ran — one that ran before this registry reached the chain, or
/// before its writer started recording at all.
///
/// It exists so that a test can decide what to assert by reading what happened
/// on chain rather than by reading the clock. Without it, a test that spans a
/// migration accepts EITHER the pre-migration or the post-migration value until
/// a hardcoded deadline, which asserts nothing at all during the one window
/// where it matters most, and red-lines on a date rather than on a fact once
/// the deadline passes. With it, a test asserts EXACTLY the value implied by
/// the migrations that have run, in both branches.
///
/// ## An index, not proof
///
/// This registry says which invariant applies. It does NOT say that the
/// invariant holds. A multisig can act out of band — a beacon is upgraded by
/// hand and nothing here moves — and then a reader would confidently assert the
/// wrong state.
///
/// So a consumer keeps both layers, with distinct jobs: this registry SELECTS
/// which invariant applies, and codehash or bytecode pins VERIFY that it
/// actually holds. Replacing the pins with this registry trades a clock-guess
/// for a bookkeeping-guess, which is not an improvement. An implementation MUST
/// NOT offer anything that invites it, and in particular MUST NOT record
/// anything about the state a migration produced — only that it was applied,
/// when, after which other records, and by which account.
///
/// The timestamp is a fact about the RECORD, not about the state: it says when
/// a migration ran and nothing whatsoever about what it did. Reading it back
/// does not become proof of anything, for the same reason reading the record
/// back does not.
///
/// ## A moment is data, and it is bounded
///
/// A moment supplied by the caller is not authenticated, and nothing else in a
/// record is either. A record is keyed by its writer and no authority checks
/// it, so every entry is exactly as trustworthy as the writer and the
/// delegates it approved: an account free to invent a migration id is free to
/// invent the moment. An implementation MUST bound it anyway, however it
/// arrived:
///
/// - NEVER ZERO (`ZeroTimestamp`). Zero is what `appliedV4` answers for a
///   migration nobody applied, so a record carrying it would read back as no
///   record while the head had moved and the migration could never be applied
///   again.
/// - NEVER AFTER THE BLOCK IT IS WRITTEN IN (`FutureTimestamp`). A record says
///   a migration HAS run. `appliedV4` therefore never answers a moment later
///   than the block asking, and a consumer whose invariant is an interval since
///   the migration — a cliff, a grace period, a rate that changes a week later
///   — subtracts it from the current block without underflowing.
/// - NEVER BEFORE THE RECORD IT IS APPLIED ONTO (`TimestampBeforeHead`). A
///   line's moments therefore never go backwards along its chain, so a
///   consumer measuring the gap between two of its migrations subtracts them
///   in chain order without underflowing either. The first migration in a
///   line is applied onto `MIGRATION_HEAD_GENESIS`, which holds no record and
///   so bounds nothing.
///
/// Nothing else constrains it, and EQUAL is accepted at both of the bounds that
/// have a neighbour: a moment may be exactly the block it is written in, and
/// two records may carry the same moment. Two migrations applied in one
/// transaction share a block and two backfilled to the same day share a
/// moment, so forcing them apart would demand a precision the moments do not
/// have. Which of them ran first is the chain, not the moments.
///
/// ## `appliedV4` answers WHEN, and zero still means "not applied"
///
/// `appliedV4` is a timestamp rather than a flag because "which invariant
/// applies" is frequently "which invariant applies YET": a migration that
/// starts a vesting cliff, a rate change, a grace period. A flag forces a
/// consumer that needs the moment to go and find the log for it, or — worse —
/// to go back to the deadline constant this registry exists to delete.
///
/// A migration nobody applied answers zero, and that is an ANSWER rather than a
/// revert: it is the ordinary state of every migration before it runs and of
/// every migration on a chain that never got it, and it is the branch a caller
/// asserts the pre-migration state in. Zero and nonzero are therefore the same
/// two distinct facts a flag carried, with the nonzero case saying more.
///
/// That distinction is only sound while a real record can never BE zero, which
/// is what `ZeroTimestamp` is for. It refuses a caller that supplies zero, and
/// it refuses `applyMigrationV4` in a block whose timestamp is zero — neither
/// hypothetical, because a test can `vm.warp(0)` and a chain can be configured
/// from a zero genesis.
///
/// ## The head is what makes an ordered sequence ordered
///
/// A LINE is one writer's records in one namespace, and it has a HEAD: the
/// migration most recently applied in it, or `MIGRATION_HEAD_GENESIS` if it
/// has never applied one. Every write names, as the first entry of its list,
/// the head the caller believes the line is at, and refuses to write unless
/// that is where the line actually is; on success the applied migration
/// becomes the new head.
///
/// Each record keeps that first entry with the rest of its list, and
/// `appliedOntoV4` reads it back. A line's records are therefore a chain in
/// storage: from `headV4`, each `appliedOntoV4` names the record before it,
/// down to `MIGRATION_HEAD_GENESIS`. That chain IS the order the migrations
/// ran in, and it is exact whatever moments the records carry.
///
/// This is what blocks a SKIPPED step. A migration script names its predecessor,
/// so a chain that never got the predecessor is a loud revert at the moment of
/// applying rather than a line that silently diverges from every other
/// chain's. It is equally what blocks two migrations dispatched concurrently
/// from landing in whichever order the mempool chose: the second one names a
/// head that has moved.
///
/// It does NOT block a DUPLICATE, and `MigrationAlreadyApplied` is not
/// redundant beside it. Re-applying a migration whose successor has since
/// landed presents a head that matches perfectly, and would move the head
/// BACKWARDS and overwrite the original timestamp — a record un-happening, which
/// is the one thing this registry promises cannot occur. The two refusals answer
/// two different questions: the head is about WHERE in the sequence a caller is,
/// and the already-applied refusal is about WHETHER this particular migration
/// has run at all.
///
/// One line on one chain is therefore ONE linear sequence, and that is a
/// consequence to design around rather than an implementation detail. Two
/// unrelated sets of migrations applied into the same writer's line in the
/// same namespace interleave into one chain of heads, so each script's
/// expected head is whatever was last applied there, by the writer or any of
/// its delegates, rather than whatever that script's own author had in mind.
///
/// ## A namespace is a line within a writer
///
/// One key writes for several repos: a CI deploy key and a token-owner Safe
/// each broadcast migrations for more than one, and every repo keeps its own
/// migration history. Under one writer alone all of those histories would
/// land in a single line with a single head, so a migration in one repo would
/// have to name, as its head, whatever the last migration in some other repo
/// was — an ordering that means nothing — and a stalled line in one repo would
/// hold the head for all of them.
///
/// So a writer's records are keyed by a NAMESPACE as well: an opaque
/// `bytes32` every write names, with one head per writer per namespace. The
/// same key keeps one line per repo, a script's expected head is the last
/// migration in ITS line, and two repos dispatching under one key contend on
/// nothing. What a namespace is — the hash of a repo's name, a fixed constant
/// beside the migration ids — is the writer's business, exactly as a migration
/// id is, and an implementation MUST NOT constrain it beyond refusing zero
/// (`ZeroNamespace`), which is what an uninitialised constant reads as and
/// never a namespace anybody meant to name. There is no plain line outside the
/// namespaces: every write names one.
///
/// A namespace is not an authority. It is the writer's to name, and a record
/// in any namespace under a writer is that writer's claim, made by it or by a
/// delegate it approved, and nobody else's. A reader that trusts a writer for
/// one namespace has said nothing about another, and asks about the one it
/// means.
///
/// ## A prerequisite is the same index, read across lines
///
/// The head orders migrations within ONE line and says nothing about any
/// other. A migration that must not run until a migration in another line has
/// — a bundle from one Safe after a fleet upgrade from another, a timelock's
/// migration after a deployer EOA's, one repo's migration after another
/// repo's under the same key — is otherwise held back by the applying script
/// re-reading the other migration's post-state, or by a runbook.
///
/// Every write takes a list of `Prerequisite`s whose first entry is the head
/// of the line being written, and reverts `PrerequisiteNotApplied` for the
/// first entry after it whose `appliedV4` is zero. A list of the head alone is
/// a migration that waits on nothing but its own predecessor.
///
/// A prerequisite is still an index, not proof. It says the other writer
/// RECORDED its migration, not that the state that migration produced holds,
/// and it is exactly as trustworthy as that writer and its delegates and no
/// more. A consumer keeps its pins. What the prerequisite removes is the
/// dependent script carrying a hand-written copy of its prerequisite's
/// post-state read.
///
/// The list is the record, and `appliedAfterV4` reads it back exactly as the
/// write gave it: the head of the line written first, then what it waited on,
/// as listed. Within one line `appliedOntoV4` walks the chain back to genesis;
/// `appliedAfterV4` walks from any record to every record it waited on, its
/// predecessor included, so the order across lines is on chain and not only in
/// the log. It says which records EXISTED when this one was written, which is
/// a fact about the record and nothing about the state around it.
///
/// A prerequisite bounds no moment. The moments in another line are that
/// writer's data, and a bound against them would let one writer's invented
/// moment refuse another writer's record. What is checked is that the record
/// EXISTS when this write lands, which is the chain's order and not the
/// moments'; a moment supplied to `applyMigrationHistoryV4` is bounded by the
/// line being written and the block, and by nothing else.
///
/// Every entry after the first is a record key in another line, and is
/// refused as `appliedV4` refuses one: `ZeroWriter`, `ZeroNamespace`,
/// `ZeroMigration` or `GenesisMigration`, none of which can name a record and
/// each of which is a constant nobody set or set to the wrong one. One in the
/// line being written — the write's `writer` AND its namespace — is
/// `OwnPrerequisite`: the first entry already says everything about that line,
/// so a later own entry is redundant if applied and unsatisfiable if not. The
/// writer's other namespaces are other lines, and a record in one of them is a
/// prerequisite like any other writer's. A prerequisite listed twice is
/// checked twice and recorded twice. The first entry is not a key: it is the
/// head, which may be `MIGRATION_HEAD_GENESIS`, and it is checked against the
/// line rather than read as a record.
///
/// ## The writer and its delegates are the whole access control
///
/// A record is keyed by its writer, and only the writer, or an account it has
/// approved for that namespace, may write it. Anyone may write, but only into
/// their own lines or lines they were approved for, so a reader that reads the
/// lines of an authority it already trusts is reading something only that
/// authority, or an account it chose, could have written. Records under any
/// other writer are unforgeable garbage that no reader asks for.
///
/// This is deliberately not a root authority. The account that applies a
/// migration differs per consumer, per chain and per migration — a Safe
/// executing a bundle, a deployer EOA broadcasting a script, a timelock — so a
/// single root would have to be all of them at once. It is also what lets the
/// implementation be identical for every consumer, and therefore live at one
/// deterministic address on every chain: an authority baked into creation code
/// would give every consumer a different address, which is the property this
/// registry exists inside a deterministic-deploy library to keep.
///
/// A compromised writer can therefore only lie about its own migrations, to
/// readers that have chosen to trust it. It cannot touch anybody else's record,
/// and it cannot unrecord its own.
///
/// ## Delegation is per writer and per namespace
///
/// Only `writer` decides who writes its line. An approval names one namespace
/// under the approving writer and nothing else, so approving a delegate for one
/// line never lets it write another, and anyone may own a namespace of the same
/// name under their own address. The events and errors are
/// `IRegistryDelegatesV2`'s, whose account is the writer and whose scope is
/// the namespace.
///
/// This decouples a line from whichever account executes a migration. A Safe
/// that changes contracts directly and a timelock that executes scheduled
/// changes can both write one line, approved by whoever owns it, so moving a
/// role between them never moves where its records go.
///
/// The writer can always write its own line, approved or not. Revoking stops
/// later writes and nothing else: records a delegate wrote while approved
/// stay, as every record does. So a line is only as trustworthy as every
/// delegate it has ever had, revoked ones included, and each record keeps the
/// account that wrote it (`appliedByV4`) so a reader can say which of them it
/// trusts.
///
/// An approved delegate can also move the line's head onto any id, which no
/// write can undo, so a compromised delegate can stop every script queued
/// against the line, leaving a new namespace as the only way out. Approve only
/// accounts held to the writer's own custody, and revoke before rotating one
/// out. Approvals cannot be enumerated here, only asked about one delegate at
/// a time, so a consumer's prod tests assert `approvedV4` is false for every
/// retired delegate beside the true answers for the live ones.
///
/// ## Identity is opaque
///
/// A migration is an opaque 32-byte value. This interface says nothing about
/// how one is derived — hashed from a script path, a name, a counter — and an
/// implementation MUST NOT constrain it beyond the two values the head space
/// reserves: zero, which is what an empty line holds before it is read as
/// genesis, and `MIGRATION_HEAD_GENESIS`, which is what it reads as. Neither can
/// be a migration without a head losing the ability to say whether a line
/// has applied anything. Two callers agreeing on any other id is entirely their
/// business.
///
/// The convention that suits scripts-as-migrations is the hash of the script's
/// identity, e.g. `keccak256("script/20260623-upgrade-receipt-vaults.s.sol")`.
/// A date alone is not enough: two migrations authored on one day collide, and
/// consumers do author two on one day. An id is fixed at the moment it is first
/// applied, so a script renamed afterwards keeps the id it was applied under
/// rather than acquiring a new one — which is why the id belongs in a named
/// constant beside the script, not derived from a path at the call site.
///
/// A head is an id, so the same is true of the head a script names: it is the
/// predecessor's named constant, imported, not a second spelling of it. So is
/// a prerequisite's migration: the other script's named constant, imported
/// from wherever that script keeps it. A namespace is the same kind of value
/// and follows the same convention: one named constant per repo, beside its
/// migration ids, named by every write in that repo and by every reader of
/// its line.
///
/// ## Metadata
///
/// A write may carry rain metadata, emitted as `MetaV1_2` with subject
/// `keccak256(abi.encode(writer, namespace, migration))`, the record it
/// describes. Non-empty metadata without the rain meta magic number reverts
/// `NotRainMetaV1`; metadata is never stored and its body never validated, and
/// an empty one emits nothing.
interface IMigrationRegistryV4 is IRegistryDelegatesV2, IMetaV1_2 {
    /// Thrown when a write is called with the zero migration id or given a
    /// prerequisite naming it, and by `appliedV4`, `appliedOntoV4`,
    /// `appliedAfterV4` and `appliedByV4` when asked about one. The zero id is
    /// what an uninitialised `bytes32` constant reads as, and an uninitialised
    /// id is never a migration anybody meant to name. Rejected in every
    /// direction because the read is the dangerous one: answering zero would
    /// silently send a caller down its pre-migration branch, and a prerequisite
    /// answered zero would be refused as unapplied forever rather than as the
    /// mistake it is.
    ///
    /// There is no matching refusal for a zero HEAD in the first entry, and
    /// adding one would be a guard on something already impossible: a head is
    /// either `MIGRATION_HEAD_GENESIS` or an applied id, both nonzero, so a
    /// zero head can never match and is already refused by
    /// `UnexpectedMigrationHead` — which names the zero it was handed, so
    /// nothing about the mistake is lost.
    error ZeroMigration();

    /// Thrown when a write is called with `MIGRATION_HEAD_GENESIS` as the
    /// migration or given a prerequisite naming it, and by `appliedV4`,
    /// `appliedOntoV4`, `appliedAfterV4` and `appliedByV4` when asked about it.
    /// Genesis is a head, not a migration: applying it would leave a line that
    /// has applied something at a head no different from one that has applied
    /// nothing, and asking `appliedV4` about it would answer zero forever for a
    /// caller that has confused a head for a migration and will read that as
    /// its pre-migration branch.
    ///
    /// This is the same refusal as `ZeroMigration` under a different diagnosis,
    /// and they are separate errors because the mistakes are different: a zero
    /// is a constant nobody set, and this is a constant set to the wrong one of
    /// two that sit beside each other.
    error GenesisMigration();

    /// Thrown by a write naming the zero writer, before anything else; by a
    /// write given a prerequisite naming it; by every read when asked about it,
    /// `approvedV4` included. No transaction can originate from the zero
    /// address, so it can neither write nor approve, every line under it is
    /// provably empty, and the answer would always be "nothing applied, at
    /// genesis" — an unresolved or unset writer constant would therefore read
    /// as a pristine line rather than as the mistake it is, and as a
    /// prerequisite it would be refused as unapplied forever rather than as
    /// that mistake.
    ///
    /// The first entry's writer must BE the write's `writer`, so a zero there
    /// is `UnexpectedMigrationHead` rather than this.
    error ZeroWriter();

    /// Thrown by every write that `writer` makes with the zero namespace (any
    /// other caller is `NotApproved` first, as no approval names it) or that is
    /// given a prerequisite naming it, by every read when asked about it, and by
    /// `approveV4`, `revokeV4` and `approvedV4` when given it. Zero is what an
    /// uninitialised `bytes32` constant reads as, so it is never a namespace
    /// anybody meant to name: a write into it would put a record where no
    /// reader that set its constant will look, a read of it would answer a
    /// pristine line about whatever the caller meant to ask, an approval in it
    /// would approve a line nobody writes, and a prerequisite in it would be
    /// refused as unapplied forever rather than as the mistake it is.
    error ZeroNamespace();

    /// Thrown when a migration already applied in a line is applied in it
    /// again. This is what makes running a migration twice structurally
    /// impossible rather than a warning in a workflow dropdown asking a human
    /// not to re-dispatch it: a script consults `appliedV4` before it acts, and
    /// this is the backstop under that consultation.
    ///
    /// Checked AFTER the head and the entries after it, so it is reached only
    /// by a write whose list holds. A re-dispatched script names the head it
    /// named the first time, which the line has since moved past, and is
    /// told so; one naming the current head is told the migration already ran.
    /// @param writer The line's writer.
    /// @param namespace The namespace the write named.
    /// @param migration The migration already applied in that line.
    error MigrationAlreadyApplied(address writer, bytes32 namespace, bytes32 migration);

    /// Thrown when the first entry of a write's list is not the head of the
    /// line being written: the list is empty, the entry's writer is not the
    /// write's `writer`, its namespace is not the one the write named, or its
    /// migration is not the head. Either something the caller believed had
    /// been applied has not been, or something it did not know about has been
    /// — a skipped predecessor, a concurrent dispatch that landed first, or a
    /// chain that is simply further behind than the script assumed.
    ///
    /// Checked first of everything about the list, before any entry after the
    /// head and before `MigrationAlreadyApplied`: the list is checked in the
    /// order it is written, and a script at the wrong place in its sequence is
    /// told so before anything else about it is.
    /// @param writer The line's writer.
    /// @param namespace The namespace the write named.
    /// @param expectedWriter The first entry's writer, or zero for an empty
    /// list.
    /// @param expectedNamespace The first entry's namespace, or zero for an
    /// empty list.
    /// @param expectedHead The first entry's migration, or zero for an empty
    /// list.
    /// @param actualHead The head the line is actually at.
    error UnexpectedMigrationHead(
        address writer,
        bytes32 namespace,
        address expectedWriter,
        bytes32 expectedNamespace,
        bytes32 expectedHead,
        bytes32 actualHead
    );

    /// Thrown when a write would record a zero moment:
    /// `applyMigrationHistoryV4` given zero, or `applyMigrationV4` in a block
    /// whose timestamp is zero. A record IS its moment, so a zero one would
    /// read back through `appliedV4` as no record at all, while the head moved
    /// and the migration cannot be re-applied — the worst of every branch at
    /// once. Zero is also what an uninitialised `uint256` holds, so it is
    /// refused for the same reason `ZeroMigration` is.
    error ZeroTimestamp();

    /// Thrown when `applyMigrationHistoryV4` is given an `appliedAt` after the
    /// timestamp of the block it is called in. A record says a migration HAS
    /// run, so a moment that has not arrived is not a record of anything — and
    /// a consumer measuring an interval since the migration would be
    /// subtracting a future moment from the present one.
    /// @param appliedAt The moment supplied.
    /// @param blockTimestamp The timestamp of the block the call landed in.
    error FutureTimestamp(uint256 appliedAt, uint256 blockTimestamp);

    /// Thrown when `applyMigrationHistoryV4` is given an `appliedAt` before the
    /// moment recorded against the head it is being applied onto. A record
    /// says its migration ran after the one before it in the chain, so an
    /// earlier moment contradicts the sequence the same call just named, and a
    /// consumer measuring the gap between two migrations would be subtracting
    /// the later moment from the earlier one.
    ///
    /// Equal is accepted. Two migrations applied in one transaction share a
    /// block, and two backfilled migrations known only to the same day share a
    /// moment; the chain is what tells those apart, so refusing them would
    /// demand a precision the moments do not have.
    ///
    /// The first migration in a line is never refused this way: it is
    /// applied onto `MIGRATION_HEAD_GENESIS`, which is a head rather than a
    /// migration and so holds no record and no moment to be before.
    ///
    /// Neither the head nor the line is named, because both are values the
    /// caller handed in and was told about first: a wrong head is
    /// `UnexpectedMigrationHead`.
    /// @param appliedAt The moment supplied.
    /// @param headAppliedAt The moment recorded against the head it is being
    /// applied onto.
    error TimestampBeforeHead(uint256 appliedAt, uint256 headAppliedAt);

    /// Thrown when an entry after the first of a write's list has not been
    /// applied: `appliedV4(writer, namespace, migration)` is zero. The first
    /// such entry in list order is the one named, and nothing after it has
    /// been read, so a caller waiting on several is told about one at a time
    /// — the one it has to wait for first.
    ///
    /// Named in full because the list is the caller's and can be long: which
    /// writer's which migration in which namespace is the whole of what a
    /// caller needs to know to go and find out why it has not landed. The
    /// line being written is not restated: nothing about it is what refused
    /// the write.
    ///
    /// It says the record does not exist, and nothing else. A prerequisite in
    /// a line the caller does not trust, or one whose migration produced a
    /// state that has since been undone by hand, is applied all the same:
    /// this is the index, and the pins are the proof.
    /// @param writer The writer the prerequisite named.
    /// @param namespace The namespace the prerequisite named.
    /// @param migration The migration under them that has not been applied.
    error PrerequisiteNotApplied(address writer, bytes32 namespace, bytes32 migration);

    /// Thrown when an entry after the first names the line being written: the
    /// write's `writer`, in the namespace the write named. The first entry is
    /// that line's head and says everything about it; a later own entry is
    /// redundant if applied and unsatisfiable if not, so the shape is one own
    /// entry then records in other lines. The writer's other namespaces are
    /// other lines and are not refused here.
    /// @param migration The own migration named after the head.
    error OwnPrerequisite(bytes32 migration);

    /// Emitted every time a migration is applied, by both writes. A migration
    /// is applied at most once per line, so the log is the complete history
    /// of the registry and the only way to discover a record without already
    /// knowing its writer and namespace.
    ///
    /// It carries no head, because the log is ordered and one line's entries
    /// in order ARE that line's chain of heads — each entry's migration is the
    /// head the next one was applied onto, and the first was applied onto
    /// `MIGRATION_HEAD_GENESIS`. It carries no list either: the list is the
    /// record, read back by `appliedAfterV4`.
    ///
    /// It does carry `appliedAt`, which the log does not otherwise hold: the
    /// block a log entry sits in says when the record was written, and
    /// `appliedAt` says when the migration ran.
    /// @param sender The account that called: `writer` or a delegate it
    /// approved for `namespace`.
    /// @param writer The line's writer.
    /// @param namespace The line under the writer.
    /// @param migration The migration applied.
    /// @param appliedAt The moment recorded against it.
    event Migrated(address sender, address writer, bytes32 namespace, bytes32 migration, uint256 appliedAt);

    /// Applies `migration` in `writer`'s line in `namespace`, after
    /// `prerequisites`, as having been applied in the block this call lands
    /// in. The caller is `writer` or a delegate it has approved for
    /// `namespace`.
    ///
    /// This is for a script applying its own migration, so the record lands in
    /// the same atomic unit as the change it describes — a Safe
    /// appends this call to the bundle it is already executing — and the two
    /// cannot land apart. Where they cannot be atomic, call it LAST: a record
    /// that never landed leaves a reader asserting the pre-migration state,
    /// which the verification layer then catches loudly, and leaves a re-run
    /// possible. A record that landed for a migration that did not is the
    /// harder state to get out of.
    ///
    /// It records the same record as `applyMigrationHistoryV4` and makes the
    /// same refusals in the same order, against `block.timestamp` as the moment
    /// — so a block whose timestamp is zero is `ZeroTimestamp`, and the moment
    /// can never be in the future.
    /// @param writer The line's writer. Never zero.
    /// @param namespace The line under `writer` to apply in. Never zero.
    /// @param migration The migration to apply. Never zero, never
    /// `MIGRATION_HEAD_GENESIS`.
    /// @param prerequisites What `migration` is applied after, which is what
    /// `appliedAfterV4` will answer for it. The first entry is `writer`, in
    /// `namespace`, at the head the caller believes that line is at: the
    /// migration it is applying onto, or `MIGRATION_HEAD_GENESIS` for the
    /// first migration in the line. Every later entry is a migration, under
    /// its writer in its namespace, that MUST have been applied for this
    /// write to land: none naming the zero writer, the zero namespace, the
    /// zero migration or `MIGRATION_HEAD_GENESIS`, and none in the line being
    /// written. The head alone for a migration that waits on nothing else.
    /// @param meta Rain metadata about the record, or empty for none.
    function applyMigrationV4(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        Prerequisite[] calldata prerequisites,
        bytes calldata meta
    ) external;

    /// Applies `migration` in `writer`'s line in `namespace`, after
    /// `prerequisites`, as having been applied at `appliedAt`. The caller is
    /// `writer` or a delegate it has approved for `namespace`.
    ///
    /// This is for a migration that ALREADY ran, which records the moment it ran
    /// rather than the moment it was written down.
    ///
    /// The implementation MUST first refuse `ZeroWriter` for `writer`, then
    /// `NotApproved` unless the caller is `writer` or approved by it for
    /// `namespace`. Then it MUST make the refusals about the other arguments,
    /// in argument order: `ZeroNamespace` for `namespace`, `ZeroMigration` or
    /// `GenesisMigration` for `migration`, `ZeroTimestamp` for `appliedAt`.
    /// Then it MUST check `prerequisites` in list order:
    /// `UnexpectedMigrationHead` if the list is empty or its first entry is
    /// not `writer` in `namespace` at the head that line is at; then
    /// `ZeroWriter`, `ZeroNamespace`, `ZeroMigration`, `GenesisMigration` or
    /// `OwnPrerequisite` for the first entry after the head that is not a
    /// record key in another line; then `PrerequisiteNotApplied` for the
    /// first entry after the head whose `appliedV4` is zero. Only then does it
    /// make the refusals about the line's record and the moment, in this
    /// order: `MigrationAlreadyApplied` if `migration` is already applied in
    /// the line, `TimestampBeforeHead` if `appliedAt` is before the moment
    /// recorded against the head, and `FutureTimestamp` if `appliedAt` is after
    /// `block.timestamp`. It MUST NOT provide any way to unrecord a migration,
    /// to move a head backwards, or to move a record once written. On success
    /// it MUST record `appliedAt`, `prerequisites` and the caller against
    /// `migration` in the line, make `migration` that line's new head, and
    /// emit `Migrated`, then, when `meta` is non-empty, `MetaV1_2(msg.sender,
    /// keccak256(abi.encode(writer, namespace, migration)), meta)`. A non-empty
    /// `meta` that `LibMeta.isRainMetaV1` rejects MUST revert `NotRainMetaV1`,
    /// after every other refusal. It MUST NOT store `meta` or validate its
    /// body.
    ///
    /// Who may write is settled before anything else. The caller's own
    /// arguments are refused next, before anything is read, because a
    /// malformed argument is a mistake the caller can fix now and a fact about
    /// the world is not. The list is then read as written: the head says where
    /// the caller is in the line's sequence, which is the first thing wrong
    /// with a skipped or re-dispatched script, and the entries after it are
    /// the caller's statement of the world its migration requires, which must
    /// hold before the line's own record is consulted — a record that exists
    /// while the prerequisites its script now names do not is the more
    /// alarming fact of the two, not the one to hide behind "already applied".
    ///
    /// A prerequisite that has been applied stays applied, because nothing can
    /// be unrecorded. A re-dispatched script therefore passes its list as it
    /// did the first time and is told `UnexpectedMigrationHead`, the line
    /// having moved past the head it names.
    ///
    /// Nothing is returned: every part of the record is an argument the caller
    /// just handed in, or the caller itself.
    /// @param writer The line's writer. Never zero.
    /// @param namespace The line under `writer` to apply in. Never zero.
    /// @param migration The migration to apply. Never zero, never
    /// `MIGRATION_HEAD_GENESIS`.
    /// @param appliedAt The moment `migration` was applied. Never zero, never
    /// after the block this call lands in. Not bounded by any prerequisite's
    /// moment.
    /// @param prerequisites What `migration` is applied after, in the shape
    /// `applyMigrationV4` takes.
    /// @param meta Rain metadata about the record, or empty for none.
    function applyMigrationHistoryV4(
        address writer,
        bytes32 namespace,
        bytes32 migration,
        uint256 appliedAt,
        Prerequisite[] calldata prerequisites,
        bytes calldata meta
    ) external;

    /// When `writer`'s line in `namespace` applied `migration`, as the moment
    /// recorded with the record. Zero if it never did.
    ///
    /// The implementation MUST revert `ZeroWriter`, `ZeroNamespace`,
    /// `ZeroMigration` or `GenesisMigration` rather than answering about any
    /// of them, and MUST answer zero — not revert — for a real line that has
    /// simply not applied a real migration.
    ///
    /// That zero is the deliberate difference from a registry whose reads revert
    /// on an unknown key. "This migration has not been applied here" is a
    /// legitimate, expected answer that a caller branches on and asserts the
    /// pre-migration state for; it is the ordinary state of every migration
    /// before it runs, and of every migration on a chain that never got it. A
    /// revert there would leave a caller with nothing to say about the state it
    /// is actually looking at, which is the whole failure this registry removes.
    ///
    /// Zero is unambiguous because no write records a zero moment, so no
    /// applied migration can present as an unapplied one. It is the same zero
    /// a write refuses a prerequisite on: a prerequisite is this read, made by
    /// the registry, with the zero answer turned into a revert.
    /// @param writer The writer to read. Never the zero address.
    /// @param namespace The line under `writer` to read. Never zero.
    /// @param migration The migration to ask about. Never zero, never
    /// `MIGRATION_HEAD_GENESIS`.
    /// @return The moment `migration` was applied in the line, or zero if it
    /// has not been.
    function appliedV4(address writer, bytes32 namespace, bytes32 migration) external view returns (uint256);

    /// What `migration` was applied ONTO in `writer`'s line in `namespace`:
    /// the head that line was at when the record was written, which is the
    /// first entry of `appliedAfterV4`. Zero if `migration` was never applied
    /// there.
    ///
    /// The implementation MUST revert `ZeroWriter`, `ZeroNamespace`,
    /// `ZeroMigration` or `GenesisMigration` rather than answering about any
    /// of them, and MUST answer zero — not revert — for a real line that has
    /// simply not applied a real migration.
    ///
    /// Zero is unambiguous: a head is either `MIGRATION_HEAD_GENESIS` or an
    /// applied id, both nonzero, so zero is never something a record holds.
    ///
    /// This is what makes a line's records a chain rather than a set.
    /// Walked from `headV4` back, each answer names the record before it and
    /// the walk ends at `MIGRATION_HEAD_GENESIS`, which is the order the
    /// migrations ran in whatever moments they carry.
    /// @param writer The writer to read. Never the zero address.
    /// @param namespace The line under `writer` to read. Never zero.
    /// @param migration The migration to ask about. Never zero, never
    /// `MIGRATION_HEAD_GENESIS`.
    /// @return The head `migration` was applied onto in the line, or zero if
    /// it has not been applied there.
    function appliedOntoV4(address writer, bytes32 namespace, bytes32 migration) external view returns (bytes32);

    /// What `migration` was applied AFTER in `writer`'s line in `namespace`:
    /// the list the write gave, exactly as given. The first entry is `writer`
    /// in `namespace` at the head it was applied onto, and every later entry is
    /// a record it waited on, in the order listed, duplicates included. Never
    /// empty for an applied migration, and empty if `migration` was never
    /// applied there.
    ///
    /// The implementation MUST revert `ZeroWriter`, `ZeroNamespace`,
    /// `ZeroMigration` or `GenesisMigration` rather than answering about any
    /// of them, and MUST answer empty — not revert — for a real line that has
    /// simply not applied a real migration.
    ///
    /// The head is an entry because it is something the record was applied
    /// after, and the one thing every record was: a walk from any record
    /// reaches everything it waited on through this one read. It is the one
    /// entry that may name `MIGRATION_HEAD_GENESIS`, which the first migration
    /// in a line was applied onto and which holds no record. Every other
    /// entry was applied when the record was written and nothing can be
    /// unrecorded, so every other entry names a record that exists.
    /// @param writer The writer to read. Never the zero address.
    /// @param namespace The line under `writer` to read. Never zero.
    /// @param migration The migration to ask about. Never zero, never
    /// `MIGRATION_HEAD_GENESIS`.
    /// @return The list `migration` was applied after in the line, as the
    /// write gave it.
    function appliedAfterV4(address writer, bytes32 namespace, bytes32 migration)
        external
        view
        returns (Prerequisite[] memory);

    /// The account that wrote `writer`'s record of `migration` in `namespace`:
    /// `writer`, or a delegate it had approved when the write landed. Refuses
    /// the inputs `appliedV4` refuses.
    /// @param writer The line's writer.
    /// @param namespace The line under the writer.
    /// @param migration The migration asked about.
    /// @return The account that wrote the record, zero if never applied.
    function appliedByV4(address writer, bytes32 namespace, bytes32 migration) external view returns (address);

    /// Where `writer`'s line in `namespace` currently is: the migration
    /// applied there most recently, or `MIGRATION_HEAD_GENESIS` if none has
    /// been.
    ///
    /// The implementation MUST revert `ZeroWriter` or `ZeroNamespace` rather
    /// than answering about the zero writer or the zero namespace, and MUST
    /// NEVER answer zero — an empty line is genesis, and a nonempty one is a
    /// nonzero migration id, so a zero answer could only mean the reader had
    /// reached something that is not this registry.
    ///
    /// This is a read for authoring and for diagnosis: which migration a chain
    /// is at, and therefore what the next script must name. It is NOT how a
    /// script decides that its predecessor ran — that is `appliedV4`, per
    /// migration, because a head says only what was last, not what was ever.
    /// @param writer The writer to read. Never the zero address.
    /// @param namespace The line under `writer` to read. Never zero.
    /// @return The head of `writer`'s line in `namespace`. Never zero.
    function headV4(address writer, bytes32 namespace) external view returns (bytes32);
}

src/interface/IRegistryDelegatesV2.sol

// SPDX-License-Identifier: LicenseRef-DCL-1.0
// SPDX-FileCopyrightText: Copyright (c) 2020 Rain Open Source Software Ltd
pragma solidity ^0.8.25;

/// @title IRegistryDelegatesV2
/// @notice The delegation `IConfigRegistryV4` and `IMigrationRegistryV4` share,
/// identically. An account approves a delegate to write under
/// it within one scope: a name in the config registry, a namespace in the
/// migration registry. An approval covers no other scope and no other account,
/// and does not chain.
interface IRegistryDelegatesV2 {
    /// Thrown when an approve, revoke or approved is given the zero delegate,
    /// which nothing can call from and which is what an uninitialised
    /// `address` reads as.
    error ZeroDelegate();

    /// Thrown when a write's caller is neither `account` nor approved by it
    /// within `scope`.
    /// @param account The account the write is under.
    /// @param scope The scope under the account.
    /// @param caller The account that called.
    error NotApproved(address account, bytes32 scope, address caller);

    /// Emitted when `sender` approves `delegate` to write under it within
    /// `scope`.
    /// @param sender The approving account, which is the account that called.
    /// @param scope The scope the approval covers.
    /// @param delegate The approved account.
    event Approved(address sender, bytes32 scope, address delegate);

    /// Emitted when `sender` revokes `delegate` within `scope`, whether or not
    /// `delegate` was approved.
    /// @param sender The revoking account, which is the account that called.
    /// @param scope The scope the revocation covers.
    /// @param delegate The revoked account.
    event Revoked(address sender, bytes32 scope, address delegate);

    /// Approves `delegate` to write under the caller within `scope` and emits
    /// `Approved`. Approving an approved delegate leaves it approved and still
    /// emits. Refuses a scope the registry does not key (the migration
    /// registry's `ZeroNamespace`), then `ZeroDelegate`.
    /// @param scope The scope the approval covers.
    /// @param delegate The account to approve. MUST NOT be zero.
    function approveV4(bytes32 scope, address delegate) external;

    /// Revokes `delegate`'s approval to write under the caller within `scope`
    /// and emits `Revoked`. Revoking an unapproved delegate leaves it
    /// unapproved and still emits. Refuses as `approveV4` does.
    /// @param scope The scope the revocation covers.
    /// @param delegate The account to revoke. MUST NOT be zero.
    function revokeV4(bytes32 scope, address delegate) external;

    /// Whether `account` has approved `delegate` within `scope`. Refuses an
    /// account and scope the registry does not key (the migration registry's
    /// `ZeroWriter`, then `ZeroNamespace`), then `ZeroDelegate`, rather than
    /// answering false about a question the caller did not mean to ask. The
    /// config registry keys every account, so its zero authority answers false.
    /// @param account The approving account.
    /// @param scope The scope asked about.
    /// @param delegate The account asked about.
    /// @return True when approved.
    function approvedV4(address account, bytes32 scope, address delegate) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 100000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin-contracts-5.7.0/=dependencies/@openzeppelin-contracts-5.7.0/",
    "forge-std-1.17.0/=dependencies/forge-std-1.17.0/",
    "rain-factory-0.2.5/=dependencies/rain-factory-0.2.5/",
    "rain-lib-memkv-0.2.0/=dependencies/rain-lib-memkv-0.2.0/",
    "rain-metadata-0.1.43/=dependencies/rain-metadata-0.1.43/",
    "rain-sol-codegen-0.1.39/=dependencies/rain-sol-codegen-0.1.39/",
    "safe-global-safe-smart-account-1.4.1-3/=dependencies/safe-global-safe-smart-account-1.4.1-3/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.