Skip to content
Verified contractPartialGPL-3.0

KeyApprovalModule

Address0x540e87aafdded146aac5905c7c39b1fe249f3ca1
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
GPL-3.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,435,637
Creation transaction
0x0c9fbb66f3…5aec5f760b
Libraries
dependencies/trex-develop/contracts/token/TokenGuardsLib.sol:TokenGuardsLib0xc8e4…27bf58dependencies/trex-develop/contracts/token/TokenLedgerLib.sol:TokenLedgerLib0x543f…dbbf0bdependencies/trex-develop/contracts/token/TokenRecoveryLib.sol:TokenRecoveryLib0x5231…fbf9b4dependencies/trex-develop/contracts/interop/TREXMessagingLib.sol:TREXMessagingLib0x4142…75c5c9dependencies/trex-develop/contracts/token/TokenDelegationLib.sol:TokenDelegationLib0x52d2…4f45bedependencies/trex-develop/contracts/compliance/modular/ModuleSetLib.sol:ModuleSetLib0xf674…14900bdependencies/trex-develop/contracts/compliance/modular/TransferValidationLib.sol:TransferValidationLib0xc492…2078d0

dependencies/onchain-id-develop/contracts/modules/executors/KeyApprovalModule.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.28;

import {
    IERC7579Execution,
    IERC7579Module,
    MODULE_TYPE_EXECUTOR,
    MODULE_TYPE_FALLBACK
} from "@openzeppelin/contracts/interfaces/draft-IERC7579.sol";

import { IERC734 } from "../../interface/IERC734.sol";
import { IKeyExecutor } from "../../interface/IKeyExecutor.sol";
import { Errors } from "../../libraries/Errors.sol";
import { hashAddress } from "../../libraries/Hashing.sol";
import { KeyPurposes } from "../../libraries/KeyPurposes.sol";

/// @dev Minimal view of the account: does a target need MANAGEMENT (self or factory)?
///      See {SmartAccount.isManagementTarget}.
interface IIdentityAccount {

    function isManagementTarget(address target) external view returns (bool);

}

/**
 * @title KeyApprovalModule
 * @notice Externalized ERC-734 `execute` / `approve` queue, served to identities via the
 *         ERC-7579 fallback handler + executor module pattern.
 *
 *         The account owns the key registry (`keyHasPurpose`); this module owns the execution
 *         queue and the auto-approval rules. Per-identity state is keyed by `account` because
 *         a single module deployment is shared across every identity that installs it.
 *
 *         Proposing vs auto-executing are separate gates. To queue a request via {execute}
 *         the caller must hold at least one of PROPOSER / ACTION / CLAIM_SIGNER /
 *         CLAIM_ADDER / MANAGEMENT on the identity. Random addresses cannot pollute the
 *         queue or the event log. PROPOSER is a queue-only purpose: it lets a key queue
 *         a request that then waits for an approver and never auto-runs by itself.
 *
 *         A queued request records the key that proposed it. Approving re-checks that key, so a
 *         request whose proposer was revoked can no longer be dispatched. Rejecting does not:
 *         any authorized approver can still close a stale entry.
 *
 *         Uninstalling the module (the executor or any of its fallback selectors) voids every
 *         request queued so far, so a pending queue cannot be resurrected across a reinstall.
 *
 *         Auto-approval rules (unchanged by the propose gate):
 *         - MANAGEMENT: anything.
 *         - ACTION: external targets only.
 *         - Anything else on self: never.
 *
 *         {execute} and {approve} only work when called through the account's ERC-7579 fallback,
 *         because that is what appends the caller for {_msgSender} to read. If the call arrives
 *         any other way, for example relayed by the EntryPoint or dispatched by the account
 *         itself, nothing is appended, so the recovered caller holds no key and the call is
 *         refused. To add or remove a claim on the identity itself, call that selector on the
 *         account directly instead of queueing it here.
 */
contract KeyApprovalModule is IERC7579Module, IKeyExecutor {

    /// @dev Per-identity queue state. One slot per installing account. Requests with an id
    ///      below `firstValidId` are void; {onUninstall} bumps the floor to the current nonce.
    struct AccountState {
        uint256 executionNonce;
        uint256 firstValidId;
        mapping(uint256 => Execution) executions;
    }

    /// @dev A queued (and possibly already-run) execution request.
    struct Execution {
        address to;
        uint256 value;
        bytes data;
        address proposer;
        bool approved;
        bool executed;
        // `executed` only says the request was attempted and is closed; it is set on a failed
        // dispatch and on a rejection too. This is the one that says the call actually landed.
        bool succeeded;
    }

    /// @dev Storage shared across all identities that install this module singleton.
    mapping(address => AccountState) private _state;

    /// @inheritdoc IERC7579Module
    function isModuleType(uint256 moduleTypeId) public pure returns (bool) {
        return moduleTypeId == MODULE_TYPE_EXECUTOR || moduleTypeId == MODULE_TYPE_FALLBACK;
    }

    /// @inheritdoc IERC7579Module
    function onInstall(bytes calldata) external pure { }

    /// @inheritdoc IERC7579Module
    /// @dev Voids every request queued so far by the uninstalling account. Runs on each
    ///      uninstall of this module (the executor or any fallback selector), so even a
    ///      partial teardown kills the queue. Fails closed: nothing here can revert.
    function onUninstall(bytes calldata) external {
        AccountState storage state = _state[msg.sender];
        uint256 nonce = state.executionNonce;
        if (state.firstValidId < nonce) {
            state.firstValidId = nonce;
            emit QueueInvalidated(msg.sender, nonce);
        }
    }

    /// @notice Queue an execution for the calling identity. Auto-runs if the caller's key
    ///         purpose authorizes it; otherwise waits for {approve}.
    /// @dev    Treasury model: any `msg.value` is pushed back to the identity; `_value` is
    ///         dispatched from the identity's balance when the request runs.
    ///         Gated: caller must hold a key on the identity that authorizes proposing.
    function execute(address _to, uint256 _value, bytes calldata _data) external payable returns (uint256 executionId) {
        address account = msg.sender;
        address proposer = _msgSender();
        bytes32 callerKeyHash = hashAddress(proposer);

        // Reject random callers. Any key with a real purpose on the identity can propose;
        // PROPOSER is the queue-only purpose for callers who should be able to push
        // requests but cannot auto-run or approve them.
        require(_canPropose(account, callerKeyHash), Errors.SenderCannotPropose(proposer));

        // 1. Push any msg.value back to the identity so the module never holds ETH.
        if (msg.value > 0) {
            (bool returned,) = account.call{ value: msg.value }("");
            require(returned, Errors.ReturnToAccountFailed());
        }

        // 2. Allocate the next execution id and persist the request.
        AccountState storage state = _state[account];
        executionId = state.executionNonce++;
        state.executions[executionId] = Execution({
            to: _to, value: _value, data: _data, proposer: proposer, approved: false, executed: false, succeeded: false
        });

        emit ExecutionRequested(account, executionId, _to, _value, _data, proposer);

        // 3. Auto-approve dispatches now; otherwise the request stays pending for {approve}.
        if (_canAutoApprove(account, callerKeyHash, _to)) {
            _runApproved(account, executionId, proposer);
        }
    }

    /// @notice Approve (or reject) a queued execution. Management-grade targets (the account, its
    ///         factory, or the key registry) require MANAGEMENT; other external targets require ACTION.
    /// @dev    This gate is target-level (MANAGEMENT vs ACTION). Per-selector claim granularity (e.g.
    ///         addClaim needing only CLAIM_SIGNER) is handled by the claim branch in `_canAutoApprove`
    ///         and the account's fallback dispatch, not here.
    function approve(uint256 _id, bool _shouldApprove) external returns (bool success) {
        // 1. Resolve account + ERC-2771 caller, fetch the queued request.
        address account = msg.sender;
        address approver = _msgSender();
        bytes32 callerKeyHash = hashAddress(approver);
        AccountState storage state = _state[account];
        Execution storage execution = state.executions[_id];

        // 2. Sanity-check the request id, that it wasn't voided by an uninstall, and that
        //    it isn't already executed.
        require(_id < state.executionNonce, Errors.InvalidRequestId());
        require(_id >= state.firstValidId, Errors.RequestInvalidated());
        require(!execution.executed, Errors.RequestAlreadyExecuted());

        // 3. Authorize the approver. A management-grade target (the account, its factory, or the
        // key registry) needs MANAGEMENT; other external targets need ACTION. Without this, an ACTION
        // key could approve a queued factory call (e.g. terminally revoke a wallet) or a registry
        // call (e.g. grant itself a MANAGEMENT key), dispatched under the module's MANAGEMENT key.
        if (IIdentityAccount(account).isManagementTarget(execution.to)) {
            require(
                IERC734(account).keyHasPurpose(callerKeyHash, KeyPurposes.MANAGEMENT),
                Errors.SenderDoesNotHaveManagementKey()
            );
        } else {
            require(
                IERC734(account).keyHasPurpose(callerKeyHash, KeyPurposes.ACTION), Errors.SenderDoesNotHaveActionKey()
            );
        }

        emit Approved(account, _id, _shouldApprove, approver);

        // 4. Approval ⇒ the key that queued the request must still be able to propose, then
        //    dispatch now. A request whose proposer was revoked cannot run, but any authorized
        //    approver can still reject it and close the stale entry.
        if (_shouldApprove) {
            require(
                _canPropose(account, hashAddress(execution.proposer)),
                Errors.ProposerNoLongerAuthorized(execution.proposer)
            );
            return _runApproved(account, _id, approver);
        }
        execution.executed = true;
        execution.approved = false;
        return false;
    }

    /// @notice Current execution nonce for the calling identity.
    function getCurrentNonce() external view returns (uint256) {
        return _state[msg.sender].executionNonce;
    }

    /// @notice Returns a queued execution by `account` and `executionId`.
    function getExecutionData(address account, uint256 executionId) external view returns (Execution memory) {
        return _state[account].executions[executionId];
    }

    /// @dev Auto-approval policy. See contract NatSpec for the rule table. Module targets are
    ///      not special-cased here: the account itself refuses to dispatch into its own modules
    ///      (see {SmartAccount}), so such a request just fails there and emits `ExecutionFailed`.
    function _canAutoApprove(address account, bytes32 keyHash, address to) internal view returns (bool) {
        // OZ rewrites to 0 to the account before dispatch, so treat it as a self-call.
        if (to == address(0)) to = account;

        // MANAGEMENT keys pass any check.
        if (IERC734(account).keyHasPurpose(keyHash, KeyPurposes.MANAGEMENT)) {
            return true;
        }

        // Self-targeted calls never auto-approve below MANAGEMENT. There used to be a rule here
        // letting claim keys auto-approve addClaim/removeClaim on self, but it could never work.
        // `_runApproved` dispatches through `executeFromExecutor`, so the account calls the claim
        // selector on itself and the fallback appends the account as the ERC-2771 caller. The
        // claim registry then looks for a claim key on the account, finds none, and reverts. The
        // try/catch turned that into a silent `ExecutionFailed`. Claim keys should call addClaim
        // or removeClaim on the account directly.
        if (to == account) return false;

        // A management-grade target (the factory or the key registry) never auto-approves for a
        // non-MANAGEMENT key; MANAGEMENT already returned above.
        if (IIdentityAccount(account).isManagementTarget(to)) return false;

        // External target: ACTION keys can dispatch directly.
        if (to != account && IERC734(account).keyHasPurpose(keyHash, KeyPurposes.ACTION)) return true;

        return false;
    }

    /// @dev Gate for {execute}. Any purpose that can already authorize an auto-run or an
    ///      approval also passes here, plus the queue-only PROPOSER purpose. MANAGEMENT is
    ///      implicit: `keyHasPurpose` returns true for a MANAGEMENT key on any queried purpose.
    function _canPropose(address account, bytes32 keyHash) internal view returns (bool) {
        IERC734 acct = IERC734(account);
        return acct.keyHasPurpose(keyHash, KeyPurposes.PROPOSER) || acct.keyHasPurpose(keyHash, KeyPurposes.ACTION)
            || acct.keyHasPurpose(keyHash, KeyPurposes.CLAIM_SIGNER)
            || acct.keyHasPurpose(keyHash, KeyPurposes.CLAIM_ADDER);
    }

    /// @dev Dispatches via `executeFromExecutor`, which spends `execution.value` from the
    ///      identity's balance. try/catch so a failed dispatch emits `ExecutionFailed`
    ///      instead of reverting.
    /// @dev `executed`/`approved` are written before the dispatch on purpose: they are what stops
    ///      the target re-entering {approve} on the same id. They therefore cannot double as a
    ///      success flag, so the outcome is recorded separately in `succeeded`.
    function _runApproved(address account, uint256 executionId, address executor) internal returns (bool success) {
        Execution storage execution = _state[account].executions[executionId];

        execution.executed = true;
        execution.approved = true;

        address to = execution.to;
        uint256 value = execution.value;
        bytes memory data = execution.data;

        // CALLTYPE_SINGLE + EXECTYPE_DEFAULT: all-zero mode word.
        bytes32 mode = bytes32(0);
        bytes memory executionCalldata = abi.encodePacked(to, value, data);

        try IERC7579Execution(account).executeFromExecutor(mode, executionCalldata) returns (bytes[] memory) {
            execution.succeeded = true;
            emit Executed(account, executionId, to, value, data, executor);
            return true;
        } catch {
            emit ExecutionFailed(account, executionId, to, value, data, executor);
            return false;
        }
    }

    /// @dev Reached via the account's fallback, `msg.sender` is the account, so the real caller is
    ///      appended (ERC-2771 style) as the trailing 20 bytes; we read it from there.
    /// @dev We can trust that tail because {SmartAccount} blocks the only path that could forge it
    ///      (a direct call to this module, which arrives with no appended tail).
    /// @dev The length check only says a tail could fit, not that one was actually appended. On a
    ///      path that skips the fallback the last 20 bytes are just ABI arguments, so the caller
    ///      reads back as some address that holds no key and the call is refused. We ask for a
    ///      selector plus the tail, so a call too short to carry one uses `msg.sender` instead.
    function _msgSender() internal view returns (address sender) {
        if (msg.data.length >= 24) {
            // solhint-disable-next-line no-inline-assembly
            assembly ("memory-safe") {
                sender := shr(96, calldataload(sub(calldatasize(), 20)))
            }
        } else {
            sender = msg.sender;
        }
    }

}

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC4337.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (interfaces/IERC4337.sol)

pragma solidity >=0.8.4;

/**
 * @dev A https://github.com/ethereum/ercs/blob/master/ERCS/erc-4337.md#useroperation[user operation] is composed of the following elements:
 * - `sender` (`address`): The account making the operation
 * - `nonce` (`uint256`): Anti-replay parameter (see “Semi-abstracted Nonce Support” )
 * - `factory` (`address`): account factory, only for new accounts
 * - `factoryData` (`bytes`): data for account factory (only if account factory exists)
 * - `callData` (`bytes`): The data to pass to the sender during the main execution call
 * - `callGasLimit` (`uint256`): The amount of gas to allocate the main execution call
 * - `verificationGasLimit` (`uint256`): The amount of gas to allocate for the verification step
 * - `preVerificationGas` (`uint256`): Extra gas to pay the bundler
 * - `maxFeePerGas` (`uint256`): Maximum fee per gas (similar to EIP-1559 max_fee_per_gas)
 * - `maxPriorityFeePerGas` (`uint256`): Maximum priority fee per gas (similar to EIP-1559 max_priority_fee_per_gas)
 * - `paymaster` (`address`): Address of paymaster contract, (or empty, if account pays for itself)
 * - `paymasterVerificationGasLimit` (`uint256`): The amount of gas to allocate for the paymaster validation code
 * - `paymasterPostOpGasLimit` (`uint256`): The amount of gas to allocate for the paymaster post-operation code
 * - `paymasterData` (`bytes`): Data for paymaster (only if paymaster exists)
 * - `signature` (`bytes`): Data passed into the account to verify authorization
 *
 * When passed to on-chain contracts, the following packed version is used.
 * - `sender` (`address`)
 * - `nonce` (`uint256`)
 * - `initCode` (`bytes`): concatenation of factory address and factoryData (or empty)
 * - `callData` (`bytes`)
 * - `accountGasLimits` (`bytes32`): concatenation of verificationGas (16 bytes) and callGas (16 bytes)
 * - `preVerificationGas` (`uint256`)
 * - `gasFees` (`bytes32`): concatenation of maxPriorityFeePerGas (16 bytes) and maxFeePerGas (16 bytes)
 * - `paymasterAndData` (`bytes`): concatenation of paymaster fields (or empty)
 *   For EntryPoint v0.9+, may optionally include `paymasterSignature` at the end:
 *   `paymaster || paymasterVerificationGasLimit || paymasterPostOpGasLimit || paymasterData || paymasterSignature || paymasterSignatureSize || PAYMASTER_SIG_MAGIC`
 * - `signature` (`bytes`)
 */
struct PackedUserOperation {
    address sender;
    uint256 nonce;
    bytes initCode; // `abi.encodePacked(factory, factoryData)`
    bytes callData;
    bytes32 accountGasLimits; // `abi.encodePacked(verificationGasLimit, callGasLimit)` 16 bytes each
    uint256 preVerificationGas;
    bytes32 gasFees; // `abi.encodePacked(maxPriorityFeePerGas, maxFeePerGas)` 16 bytes each
    bytes paymasterAndData; // `abi.encodePacked(paymaster, paymasterVerificationGasLimit, paymasterPostOpGasLimit, paymasterData[, paymasterSignature, paymasterSignatureSize, PAYMASTER_SIG_MAGIC])` (20 bytes, 16 bytes, 16 bytes, dynamic[, dynamic, 2 bytes, 8 bytes])
    bytes signature;
}

/**
 * @dev Aggregates and validates multiple signatures for a batch of user operations.
 *
 * A contract could implement this interface with custom validation schemes that allow signature aggregation,
 * enabling significant optimizations and gas savings for execution and transaction data cost.
 *
 * Bundlers and clients whitelist supported aggregators.
 *
 * See https://eips.ethereum.org/EIPS/eip-7766[ERC-7766]
 */
interface IAggregator {
    /**
     * @dev Validates the signature for a user operation.
     * Returns an alternative signature that should be used during bundling.
     */
    function validateUserOpSignature(
        PackedUserOperation calldata userOp
    ) external view returns (bytes memory sigForUserOp);

    /**
     * @dev Returns an aggregated signature for a batch of user operation's signatures.
     */
    function aggregateSignatures(
        PackedUserOperation[] calldata userOps
    ) external view returns (bytes memory aggregatesSignature);

    /**
     * @dev Validates that the aggregated signature is valid for the user operations.
     *
     * Requirements:
     *
     * - The aggregated signature MUST match the given list of operations.
     */
    function validateSignatures(PackedUserOperation[] calldata userOps, bytes calldata signature) external view;
}

/**
 * @dev Handle nonce management for accounts.
 *
 * Nonces are used in accounts as a replay protection mechanism and to ensure the order of user operations.
 * To avoid limiting the number of operations an account can perform, the interface allows using parallel
 * nonces by using a `key` parameter.
 *
 * See https://eips.ethereum.org/EIPS/eip-4337#semi-abstracted-nonce-support[ERC-4337 semi-abstracted nonce support].
 */
interface IEntryPointNonces {
    /**
     * @dev Returns the nonce for a `sender` account and a `key`.
     *
     * Nonces for a certain `key` are always increasing.
     */
    function getNonce(address sender, uint192 key) external view returns (uint256 nonce);
}

/**
 * @dev Handle stake management for entities (i.e. accounts, paymasters, factories).
 *
 * The EntryPoint must implement the following API to let entities like paymasters have a stake,
 * and thus have more flexibility in their storage access
 * (see https://eips.ethereum.org/EIPS/eip-4337#reputation-scoring-and-throttlingbanning-for-global-entities[reputation, throttling and banning.])
 */
interface IEntryPointStake {
    /**
     * @dev Returns the balance of the account.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Deposits `msg.value` to the account.
     */
    function depositTo(address account) external payable;

    /**
     * @dev Withdraws `withdrawAmount` from the account to `withdrawAddress`.
     */
    function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;

    /**
     * @dev Adds stake to the account with an unstake delay of `unstakeDelaySec`.
     */
    function addStake(uint32 unstakeDelaySec) external payable;

    /**
     * @dev Unlocks the stake of the account.
     */
    function unlockStake() external;

    /**
     * @dev Withdraws the stake of the account to `withdrawAddress`.
     */
    function withdrawStake(address payable withdrawAddress) external;
}

/**
 * @dev Entry point for user operations.
 *
 * User operations are validated and executed by this contract.
 */
interface IEntryPoint is IEntryPointNonces, IEntryPointStake {
    /**
     * @dev A user operation at `opIndex` failed with `reason`.
     */
    error FailedOp(uint256 opIndex, string reason);

    /**
     * @dev A user operation at `opIndex` failed with `reason` and `inner` returned data.
     */
    error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);

    /**
     * @dev Batch of aggregated user operations per aggregator.
     */
    struct UserOpsPerAggregator {
        PackedUserOperation[] userOps;
        IAggregator aggregator;
        bytes signature;
    }

    /**
     * @dev Executes a batch of user operations.
     * @param beneficiary Address to which gas is refunded upon completing the execution.
     */
    function handleOps(PackedUserOperation[] calldata ops, address payable beneficiary) external;

    /**
     * @dev Executes a batch of aggregated user operations per aggregator.
     * @param beneficiary Address to which gas is refunded upon completing the execution.
     */
    function handleAggregatedOps(
        UserOpsPerAggregator[] calldata opsPerAggregator,
        address payable beneficiary
    ) external;
}

/**
 * @dev Base interface for an ERC-4337 account.
 */
interface IAccount {
    /**
     * @dev Validates a user operation.
     *
     * * MUST validate the caller is a trusted EntryPoint
     * * MUST validate that the signature is a valid signature of the userOpHash, and SHOULD
     *   return SIG_VALIDATION_FAILED (and not revert) on signature mismatch. Any other error MUST revert.
     * * MUST pay the entryPoint (caller) at least the “missingAccountFunds” (which might
     *   be zero, in case the current account’s deposit is high enough)
     *
     * Returns an encoded packed validation data that is composed of the following elements:
     *
     * - `authorizer` (`address`): 0 for success, 1 for failure, otherwise the address of an authorizer contract
     * - `validUntil` (`uint48`): The UserOp is valid only up to this time. Zero for “infinite”.
     * - `validAfter` (`uint48`): The UserOp is valid only after this time.
     */
    function validateUserOp(
        PackedUserOperation calldata userOp,
        bytes32 userOpHash,
        uint256 missingAccountFunds
    ) external returns (uint256 validationData);
}

/**
 * @dev Support for executing user operations by prepending the {executeUserOp} function selector
 * to the UserOperation's `callData`.
 */
interface IAccountExecute {
    /**
     * @dev Executes a user operation.
     */
    function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external;
}

/**
 * @dev Interface for a paymaster contract that agrees to pay for the gas costs of a user operation.
 *
 * NOTE: A paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
 */
interface IPaymaster {
    enum PostOpMode {
        opSucceeded,
        opReverted,
        postOpReverted
    }

    /**
     * @dev Validates whether the paymaster is willing to pay for the user operation. See
     * {IAccount-validateUserOp} for additional information on the return value.
     *
     * NOTE: Bundlers will reject this method if it modifies the state, unless it's whitelisted.
     */
    function validatePaymasterUserOp(
        PackedUserOperation calldata userOp,
        bytes32 userOpHash,
        uint256 maxCost
    ) external returns (bytes memory context, uint256 validationData);

    /**
     * @dev Verifies the sender is the entrypoint.
     * @param actualGasCost the actual amount paid (by account or paymaster) for this UserOperation
     * @param actualUserOpFeePerGas total gas used by this UserOperation (including preVerification, creation, validation and execution)
     */
    function postOp(
        PostOpMode mode,
        bytes calldata context,
        uint256 actualGasCost,
        uint256 actualUserOpFeePerGas
    ) external;
}

dependencies/@openzeppelin-contracts-5.7.0/interfaces/draft-IERC7579.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (interfaces/draft-IERC7579.sol)

pragma solidity >=0.8.4;

import {PackedUserOperation} from "./IERC4337.sol";

uint256 constant VALIDATION_SUCCESS = 0;
uint256 constant VALIDATION_FAILED = 1;
uint256 constant MODULE_TYPE_VALIDATOR = 1;
uint256 constant MODULE_TYPE_EXECUTOR = 2;
uint256 constant MODULE_TYPE_FALLBACK = 3;
uint256 constant MODULE_TYPE_HOOK = 4;

/// @dev Minimal configuration interface for ERC-7579 modules
interface IERC7579Module {
    /**
     * @dev This function is called by the smart account during installation of the module
     * @param data arbitrary data that may be passed to the module during `onInstall` initialization
     *
     * MUST revert on error (e.g. if module is already enabled)
     */
    function onInstall(bytes calldata data) external;

    /**
     * @dev This function is called by the smart account during uninstallation of the module
     * @param data arbitrary data that may be passed to the module during `onUninstall` de-initialization
     *
     * MUST revert on error
     */
    function onUninstall(bytes calldata data) external;

    /**
     * @dev Returns boolean value if module is a certain type
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     *
     * MUST return true if the module is of the given type and false otherwise
     */
    function isModuleType(uint256 moduleTypeId) external view returns (bool);
}

/**
 * @dev ERC-7579 Validation module (type 1).
 *
 * A module that implements logic to validate user operations and signatures.
 */
interface IERC7579Validator is IERC7579Module {
    /**
     * @dev Validates a UserOperation
     * @param userOp the ERC-4337 PackedUserOperation
     * @param userOpHash the hash of the ERC-4337 PackedUserOperation
     *
     * MUST validate that the signature is a valid signature of the userOpHash
     * SHOULD return ERC-4337's SIG_VALIDATION_FAILED (and not revert) on signature mismatch
     * See {IAccount-validateUserOp} for additional information on the return value
     */
    function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external returns (uint256);

    /**
     * @dev Validates a signature using ERC-1271
     * @param sender the address that sent the ERC-1271 request to the smart account
     * @param hash the hash of the ERC-1271 request
     * @param signature the signature of the ERC-1271 request
     *
     * MUST return the ERC-1271 `MAGIC_VALUE` if the signature is valid
     * MUST NOT modify state
     */
    function isValidSignatureWithSender(
        address sender,
        bytes32 hash,
        bytes calldata signature
    ) external view returns (bytes4);
}

/**
 * @dev ERC-7579 Hooks module (type 4).
 *
 * A module that implements logic to execute before and after the account executes a user operation,
 * either individually or batched.
 */
interface IERC7579Hook is IERC7579Module {
    /**
     * @dev Called by the smart account before execution
     * @param msgSender the address that called the smart account
     * @param value the value that was sent to the smart account
     * @param msgData the data that was sent to the smart account
     *
     * MAY return arbitrary data in the `hookData` return value
     */
    function preCheck(
        address msgSender,
        uint256 value,
        bytes calldata msgData
    ) external returns (bytes memory hookData);

    /**
     * @dev Called by the smart account after execution
     * @param hookData the data that was returned by the `preCheck` function
     *
     * MAY validate the `hookData` to validate transaction context of the `preCheck` function
     */
    function postCheck(bytes calldata hookData) external;
}

struct Execution {
    address target;
    uint256 value;
    bytes callData;
}

/**
 * @dev ERC-7579 Execution.
 *
 * Accounts should implement this interface so that the Entrypoint and ERC-7579 modules can execute operations.
 */
interface IERC7579Execution {
    /**
     * @dev Executes a transaction on behalf of the account.
     * @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
     * @param executionCalldata The encoded execution call data
     *
     * MUST ensure adequate authorization control: e.g. onlyEntryPointOrSelf if used with ERC-4337
     * If a mode is requested that is not supported by the Account, it MUST revert
     */
    function execute(bytes32 mode, bytes calldata executionCalldata) external payable;

    /**
     * @dev Executes a transaction on behalf of the account.
     *         This function is intended to be called by Executor Modules
     * @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
     * @param executionCalldata The encoded execution call data
     * @return returnData An array with the returned data of each executed subcall
     *
     * MUST ensure adequate authorization control: i.e. onlyExecutorModule
     * If a mode is requested that is not supported by the Account, it MUST revert
     */
    function executeFromExecutor(
        bytes32 mode,
        bytes calldata executionCalldata
    ) external payable returns (bytes[] memory returnData);
}

/**
 * @dev ERC-7579 Account Config.
 *
 * Accounts should implement this interface to expose information that identifies the account, supported modules and capabilities.
 */
interface IERC7579AccountConfig {
    /**
     * @dev Returns the account id of the smart account
     * @return accountImplementationId the account id of the smart account
     *
     * MUST return a non-empty string
     * The accountId SHOULD be structured like so:
     *        "vendorname.accountname.semver"
     * The id SHOULD be unique across all smart accounts
     */
    function accountId() external view returns (string memory accountImplementationId);

    /**
     * @dev Function to check if the account supports a certain execution mode (see above)
     * @param encodedMode the encoded mode
     *
     * MUST return true if the account supports the mode and false otherwise
     */
    function supportsExecutionMode(bytes32 encodedMode) external view returns (bool);

    /**
     * @dev Function to check if the account supports a certain module typeId
     * @param moduleTypeId the module type ID according to the ERC-7579 spec
     *
     * MUST return true if the account supports the module type and false otherwise
     */
    function supportsModule(uint256 moduleTypeId) external view returns (bool);
}

/**
 * @dev ERC-7579 Module Config.
 *
 * Accounts should implement this interface to allow installing and uninstalling modules.
 */
interface IERC7579ModuleConfig {
    event ModuleInstalled(uint256 moduleTypeId, address module);
    event ModuleUninstalled(uint256 moduleTypeId, address module);

    /**
     * @dev Installs a Module of a certain type on the smart account
     * @param moduleTypeId the module type ID according to the ERC-7579 spec
     * @param module the module address
     * @param initData arbitrary data that may be passed to the module during `onInstall`
     * initialization.
     *
     * MUST implement authorization control
     * MUST call `onInstall` on the module with the `initData` parameter if provided
     * MUST emit ModuleInstalled event
     * MUST revert if the module is already installed or the initialization on the module failed
     */
    function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external;

    /**
     * @dev Uninstalls a Module of a certain type on the smart account
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param deInitData arbitrary data that may be passed to the module during `onUninstall`
     * deinitialization.
     *
     * MUST implement authorization control
     * MUST call `onUninstall` on the module with the `deInitData` parameter if provided
     * MUST emit ModuleUninstalled event
     * MUST revert if the module is not installed or the deInitialization on the module failed
     */
    function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external;

    /**
     * @dev Returns whether a module is installed on the smart account
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param additionalContext arbitrary data that may be passed to determine if the module is installed
     *
     * MUST return true if the module is installed and false otherwise
     */
    function isModuleInstalled(
        uint256 moduleTypeId,
        address module,
        bytes calldata additionalContext
    ) external view returns (bool);
}

dependencies/onchain-id-develop/contracts/interface/IERC734.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.27;

/**
 * @dev Interface of the ERC734 (Key Holder) standard as defined in the EIP, registry-only.
 *
 * @notice The original `execute(address,uint256,bytes)` and `approve(uint256,bool)` selectors
 *         live in the {KeyApprovalModule} (an ERC-7579 fallback handler + executor). They are
 *         still reachable on every Identity at the standard ERC-734 selectors via the account's
 *         fallback, but they live behind a separate Solidity type — {IKeyExecutor} — to keep
 *         the registry interface decoupled from the execution surface.
 *
 *         See {IKeyExecutor} for the queue ABI, and {KeyApprovalModule} for the implementation.
 *
 *         Note on events: this interface declares none. The key registry and the execution
 *         queue are served by module singletons shared across identities, so the canonical
 *         ERC-734 events (which carry no subject) could not attribute a log to an identity.
 *         The real event ABI is the account-carrying variants — `KeyAdded` / `KeyRemoved` on
 *         {ERC734Validator} and the execution lifecycle events on {IKeyExecutor} — each with
 *         `address indexed account` (the identity) as its first field.
 */
interface IERC734 {

    /**
     * @dev Adds a _key to the identity. MUST only be done by keys of purpose MANAGEMENT,
     * or the identity itself.
     */
    function addKey(bytes32 _key, uint256 _purpose, uint256 _keyType) external returns (bool success);

    /**
     * @dev Removes _purpose for _key from the identity. MUST only be done by keys of purpose
     * MANAGEMENT, or the identity itself.
     */
    function removeKey(bytes32 _key, uint256 _purpose) external returns (bool success);

    /// @dev Returns the full key data, if present.
    function getKey(bytes32 _key) external view returns (uint256[] memory purposes, uint256 keyType, bytes32 key);

    /// @dev Returns the purposes for a key.
    function getKeyPurposes(bytes32 _key) external view returns (uint256[] memory _purposes);

    /// @dev Returns the key hashes registered with a given purpose.
    function getKeysByPurpose(uint256 _purpose) external view returns (bytes32[] memory keys);

    /// @dev Returns TRUE if a key has the given purpose, or MANAGEMENT (universal).
    function keyHasPurpose(bytes32 _key, uint256 _purpose) external view returns (bool exists);

}

dependencies/onchain-id-develop/contracts/interface/IKeyExecutor.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.28;

/**
 * @title IKeyExecutor
 * @notice Externalized execution surface for ERC-734 identities, served by the
 *         {KeyApprovalModule} via the identity's ERC-7579 fallback handler.
 *
 * @dev Exposes the legacy `execute` / `approve` ABI as a separate Solidity type so that
 *      callers can `IKeyExecutor(address(identity)).execute(...)` without forcing the
 *      account contract itself to declare these as concrete methods. At the wire level
 *      these selectors are identical to the original ERC-734 selectors, so on-chain
 *      consumers keep calling them as ERC-734 calls.
 *
 *      The lifecycle events below are NOT the canonical ERC-734 ones: the queue module is a
 *      singleton emitting on its own address for every identity that installs it, so each
 *      event carries `address indexed account` (the identity) as its first field. Indexers
 *      must filter on that field, not on the emitter.
 *
 *      See {KeyApprovalModule} for the implementation and the auto-approval rule table.
 */
interface IKeyExecutor {

    /// @dev Emitted when an identity queues an execution via {execute}.
    event ExecutionRequested(
        address indexed account,
        uint256 indexed executionId,
        address indexed to,
        uint256 value,
        bytes data,
        address proposer
    );

    /// @dev Emitted when an execution is approved (or rejected) via {approve}. `approver` is the key holder that made the call (the ERC-2771 caller behind the identity).
    event Approved(address indexed account, uint256 indexed executionId, bool approved, address approver);

    /// @dev Emitted when an uninstall voids every request queued below `firstValidId`.
    event QueueInvalidated(address indexed account, uint256 firstValidId);

    /// @dev Emitted when an approved execution successfully dispatches through the account. `executor` is the
    ///      key holder whose call ran it: the proposer on an auto-run, the approver otherwise.
    event Executed(
        address indexed account,
        uint256 indexed executionId,
        address indexed to,
        uint256 value,
        bytes data,
        address executor
    );

    /// @dev Emitted when an approved execution reverts inside the account. `executor` as in {Executed}.
    event ExecutionFailed(
        address indexed account,
        uint256 indexed executionId,
        address indexed to,
        uint256 value,
        bytes data,
        address executor
    );

    /**
     * @notice Queue (and possibly auto-execute) a call from the identity.
     * @return executionId opaque id used with {approve} if the call was queued, not auto-approved.
     */
    function execute(address _to, uint256 _value, bytes calldata _data) external payable returns (uint256 executionId);

    /**
     * @notice Approve (or reject) a previously queued execution. Caller's keyHash is recovered
     *         from the ERC-2771 trailing-bytes convention.
     */
    function approve(uint256 _id, bool _shouldApprove) external returns (bool success);

    /// @notice Current execution nonce for the calling identity.
    function getCurrentNonce() external view returns (uint256);

}

dependencies/onchain-id-develop/contracts/libraries/Errors.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.27;

/// @title Errors
/// @notice Library containing all custom errors the protocol may revert with
library Errors {

    /* ----- Generic ----- */

    /// @notice Reverts if the address is zero
    error ZeroAddress();

    /* ----- IdentityFactory ----- */

    /// @notice Reverts if the list of keys is empty
    error EmptyListOfKeys();

    /// @notice Reverts if the string is empty
    error EmptyString();

    /// @notice Reverts when a caller tries to deploy an identity of a type whose
    ///         configured AM role they do not hold.
    /// @param caller the address that attempted the deployment.
    /// @param identityType the identity type that was requested.
    /// @param requiredRole the AM role id required for that type.
    error NotAuthorizedForIdentityType(address caller, uint256 identityType, uint64 requiredRole);

    /// @notice Reverts when the caller holds the type role but with a non-zero AM
    ///         execution delay. The factory has no scheduling flow, so instead of
    ///         silently ignoring the delay the call is rejected — grant per-type
    ///         roles with a zero execution delay.
    /// @param caller the address that attempted the deployment.
    /// @param requiredRole the AM role id required for that type.
    /// @param executionDelay the delay the caller's membership carries.
    error DelayedRoleNotSupported(address caller, uint64 requiredRole, uint32 executionDelay);

    /// @notice Reverts when a deploy is attempted for a type the admin has not registered.
    ///         Admin enables a type by calling `setIdentityTypePolicy`. Use the AM's
    ///         `PUBLIC_ROLE` for open types.
    error UnknownIdentityType(uint256 identityType);

    /// @notice Reverts when {setIdentityTypePolicy} is called with type 0. In the
    ///         factory's type record a 0 means "not deployed by this factory", so 0
    ///         can never be a real type.
    error ZeroIdentityType();

    /// @notice Reverts when {createIdentity} is called for a type whose policy has
    ///         `selfDeployable = false`. Self-deploy is gated per type because some
    ///         types (e.g. ASSET, SMART_CONTRACT) represent contracts, not EOAs, so
    ///         the `msg.sender = first wallet` binding does not apply to them. Admin
    ///         opts a type in via {setIdentityTypePolicy}.
    error IdentityTypeNotSelfDeployable(uint256 identityType);

    /// @notice Reverts if no key with MANAGEMENT purpose is provided
    error NoManagementKeyInKeys();

    /// @notice Reverts when {createIdentityFor} deploys for a signing type but `_account`
    ///         is not the only wallet with MANAGEMENT on the new identity. The wallet the
    ///         identity was created for has to manage it alone, or the caller could keep a
    ///         key and strip that wallet later. The type's registered modules may hold
    ///         MANAGEMENT alongside it.
    error AccountNotSoleManagementKey(address account);

    /// @notice Reverts when {createIdentityFor} deploys for a signing type and the caller
    ///         supplies a key that is not `_account`'s own key hash. The caller may only
    ///         grant purposes to the account the identity is created for; the account adds
    ///         any other keys itself once it is in control. `keyHash` is the hash derived
    ///         from the key's `signerData`, which is the value the registry stores under.
    error KeyNotForAccount(bytes32 keyHash);

    /// @notice Reverts when a deploy caller supplies a key typed MODULE. That type is
    ///         reserved for keys the module install registers: MODULE keys stay out of the
    ///         MANAGEMENT index, so a wallet key wearing it would escape the management
    ///         counts while keeping key authority.
    error CallerKeyCannotBeModule(bytes32 keyHash);

    /// @notice Reverts when {setIdentityTypePolicy} would open a single-binding type to the
    ///         AM's PUBLIC_ROLE. Single binding types skip the sole management check, so
    ///         their role gate must stay restricted.
    error SingleBindingTypeCannotBePublic(uint256 identityType);

    /// @notice Reverts when an identity is initialized with no validator and no executor
    ///         module. Without either, the account cannot verify signatures or dispatch
    ///         outbound calls.
    error IdentityNoValidatorOrExecutor();

    /// @notice Reverts when a wallet is already linked to a different identity than the one
    ///         currently trying to claim it. Sticky binding: a wallet can be re-linked only to
    ///         its original identity, never to another.
    error WalletBoundToAnotherIdentity(bytes wallet, address boundIdentity);

    /// @notice Reverts when a wallet that was previously revoked is presented to {linkAccount}.
    ///         Revocation is terminal. A wallet cannot be re-linked after being revoked.
    error WalletAlreadyRevoked(bytes wallet);

    /// @notice Reverts when an operation requires the wallet to be in the `Active` lifecycle
    ///         state (e.g. {revokeAccount}) but it is not.
    error WalletNotActive(bytes wallet);

    /// @notice Reverts when {linkAccount} is called by a contract that was not deployed by
    ///         this factory. Only factory-deployed identities can pull wallets in.
    error NotFactoryIdentity(address caller);

    /// @notice Reverts when an EIP-712 link signature is presented after its `expiry`, or
    ///         when `expiry == 0` (callers must set freshness explicitly).
    error ExpiredSignature(uint256 expiry);

    /// @notice Reverts when {linkAccount} is called on an asset identity. An asset
    ///         identity represents one specific token contract. Adding more wallets to
    ///         it would break the 1:1 token↔identity mapping.
    error CannotLinkToAssetIdentity(address identity);

    /// @notice Reverts when a factory-deployed identity is presented as an account to link
    ///         to another identity. A factory identity always resolves to itself, so binding
    ///         it as an account would make identity resolution ambiguous.
    error CannotLinkFactoryIdentity(address identity);

    /// @notice Reverts when {revokeAccount} is called on a non-signing-entity identity
    ///         (ASSET or SMART_CONTRACT). The bound contract cannot sign a fresh
    ///         {linkAccount} digest, so revoking would orphan the factory's discovery
    ///         entry permanently with no recovery path.
    error CannotRevokeFromNonSigningIdentity(address identity);

    /// @notice Reverts when a wallet is already actively linked to the calling identity.
    error WalletAlreadyLinkedToIdentity(bytes wallet);

    /// @notice Reverts when an operation references a wallet that has never been linked, or
    ///         is not currently part of the calling identity's active set.
    error WalletNotLinkedToIdentity(bytes wallet);

    /// @notice Reverts when the caller of {settlePendingCrossChainLink} does not match the
    ///         identity recorded in the pending proposal. `recorded` is `address(0)`
    ///         if no proposal exists for the wallet.
    error PendingCrossChainLinkIdentityMismatch(bytes wallet, address caller, address recorded);

    /// @notice Reverts when an inbound cross-chain proposal targets a wallet that
    ///         already has a registry entry (active or revoked). Sticky binding
    ///         applies to the cross-chain path the same way it does to the EVM path.
    error WalletAlreadyHasEntry(bytes wallet);

    /// @notice Reverts when the ERC-7786 source-chain sender does not match the
    ///         wallet envelope carried in the payload. The wallet must originate
    ///         the bridge call itself, so `sender` and `wallet` must be the same
    ///         interoperable address.
    error CrossChainSenderWalletMismatch(bytes sender, bytes wallet);

    /// @notice Reverts when a cross-chain link proposal is delivered or confirmed
    ///         past its `expiry`.
    error PendingCrossChainLinkExpired(uint256 expiry);

    /// @notice Reverts when a cross-chain proposal names a wallet on this chain.
    ///         Local wallets link through {linkAccount} with a signature.
    error CrossChainLinkForLocalWallet(bytes wallet);

    /// @notice Reverts when {linkAccount} gets an envelope whose chain type is not
    ///         eip-155. The signature path can only verify EVM signers; foreign
    ///         wallets go through the ERC-7786 cross-chain path.
    error NonEvmAccount(bytes account);

    /// @notice Reverts when {linkAccount} gets an eip-155 envelope whose chain
    ///         reference is not this chain's id in minimal big-endian form. The
    ///         signature path can only prove control on the local chain; wallets on
    ///         other EVM chains go through the ERC-7786 cross-chain path.
    error AccountNotOnLocalChain(bytes account);

    /// @notice Reverts when an ERC-7913 signer names a verifier that admin has not
    ///         approved via {setTrustedVerifier}. Without the list, a caller could
    ///         ship a verifier that accepts anything and self-certify the link.
    error UntrustedVerifier(address verifier);

    /// @notice Reverts when a wallet envelope encodes its eip-155 chain reference
    ///         with leading zero padding. The same chainid has one minimal
    ///         encoding and the registry only accepts that one.
    error NonCanonicalAccount(bytes account);

    /* ----- ClaimIssuer ----- */

    /// @notice The claim already exists.
    error ClaimAlreadyRevoked();

    /* ----- ERC734Validator trusted-issuer path ----- */

    /// @notice Reverts when the resolved issuer identity is not of type
    ///         {IdentityTypes.CLAIM_ISSUER}. The trusted-issuer path is reserved for
    ///         identities deployed under the role-gated CLAIM_ISSUER type so a high
    ///         reputation score on another type cannot grant claim-write capability.
    error IdentityNotClaimIssuerType(address identity);

    /// @notice Reverts when the resolved CLAIM_ISSUER identity's reputation score is
    ///         below the consumer's claim-add threshold.
    error ReputationBelowClaimAddThreshold(address identity, uint256 score, uint256 threshold);

    /* ----- ERC734Validator field caps (see {Structs}) ----- */

    /// @notice Reverts when a key's clientData exceeds {Structs.MAX_CLIENT_DATA_LENGTH}.
    error ClientDataTooLong();

    /// @notice Reverts when a claim's signature exceeds {Structs.MAX_CLAIM_SIGNATURE_LENGTH}.
    error ClaimSignatureTooLong();

    /// @notice Reverts when a claim's payload exceeds {Structs.MAX_CLAIM_PAYLOAD_LENGTH}.
    error ClaimPayloadTooLong();

    /// @notice Reverts when a claim's uri exceeds {Structs.MAX_CLAIM_URI_LENGTH}.
    error ClaimUriTooLong();

    /* ----- Identity ----- */

    /// @notice {IdentityFactory.initializeBeacon} was called but the beacon is already deployed.
    error BeaconAlreadyInitialized();

    /// @notice Identity deployment was attempted before {IdentityFactory.initializeBeacon}
    ///         deployed the beacon at its predetermined slot.
    error BeaconNotInitialized();

    /// @notice CREATE3 deployed the beacon somewhere other than the predetermined address the
    ///         factory committed to at construction. Only possible on chains whose CREATE2
    ///         derivation deviates from the canonical EVM formula (e.g. zkSync Era).
    error BeaconAddressMismatch(address expected, address actual);

    /// @notice The candidate beacon implementation has no code.
    error ImplementationNotAContract(address implementation);

    /// @notice The candidate beacon implementation does not name this factory as its
    ///         enshrined {IdentityFactory}.
    error ImplementationFactoryMismatch(address implementation);

    /// @notice The candidate beacon implementation still has its initializers open, so it
    ///         could be initialized directly instead of only behind a proxy.
    error ImplementationInitializersNotDisabled(address implementation);

    /// @notice The candidate beacon implementation names a different registry module than
    ///         the one every deployed identity already holds its keys in.
    error ImplementationRegistryMismatch(address expected, address actual);

    /// @notice The candidate beacon implementation reports a different version than the one
    ///         the upgrader committed to in {IdentityFactory.upgradeBeacon}.
    error ImplementationVersionMismatch(string expected, string actual);

    /// @notice The sender does not have the management key.
    error SenderDoesNotHaveManagementKey();

    /// @notice The sender does not have the claim signer key.
    error SenderDoesNotHaveClaimSignerKey();

    /// @notice The sender does not have the action key.
    error SenderDoesNotHaveActionKey();

    /// @notice The caller holds no key on the target identity that authorizes proposing an
    ///         execution. PROPOSER, ACTION, CLAIM_SIGNER, CLAIM_ADDER, or MANAGEMENT works.
    error SenderCannotPropose(address sender);

    /// @notice The key does not have the purpose.
    error KeyDoesNotHavePurpose(bytes32 key, uint256 purpose);

    /// @notice The claim is not registered.
    error ClaimNotRegistered(bytes32 claimId);

    /// @notice The request is not valid.
    error InvalidRequestId();

    /// @notice The request is already executed.
    error RequestAlreadyExecuted();

    /// @notice The key that queued the request no longer authorizes proposing on the identity.
    error ProposerNoLongerAuthorized(address proposer);

    /// @notice The request was queued before the module was last uninstalled and is void.
    error RequestInvalidated();

    /// @notice The claim is invalid.
    error InvalidClaim();

    /// @notice Topic 0 is the "no claim" sentinel and cannot be used for a stored claim.
    error InvalidClaimTopic();

    /// @notice The submitted scheme and uri do not match the metadataHash signed in the claim data.
    error ClaimMetadataMismatch(uint256 scheme, string uri);

    /* ----- SmartAccount ----- */

    /// @notice The signature is invalid.
    error InvalidSignature();

    /// @notice The signer data is invalid or too short.
    error InvalidSignerData();

    /// @notice The execution mode requested is not supported by the account's purpose check.
    error UnsupportedExecutionMode(bytes32 mode);

    /// @notice A dispatched call targeted one of the account's own modules (an installed executor,
    ///         or the fallback handler for the call's selector). Module functions are reached via
    ///         the account's fallback dispatch, never via `execute(module, ...)`. The only caller
    ///         allowed to do this is the account itself.
    error OwnModuleTargetBlocked(address target);

    /// @notice An installed executor or fallback handler tried to dispatch a call whose target
    ///         is not authorized by the purpose registered for that module at install time.
    ///         Also raised at install time if the module's initData does not begin with a
    ///         non-zero `uint256 purpose`.
    error ExecutorPurposeNotAuthorized();

    /// @notice ETH push from `KeyApprovalModule` back to the identity failed.
    error ReturnToAccountFailed();

    /* ----- EASClaimIssuer ----- */

    /// @notice Reverts when a caller invokes an `IClaimIssuer` or `IIdentity` method that has
    ///         no meaning on a stateless adapter (key management, claim storage, execution).
    ///         The adapter is a live view over EAS and holds no keys or claims.
    error EASNotSupported();

}

dependencies/onchain-id-develop/contracts/libraries/Hashing.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.27;

/// @notice Hash a 20-byte address the same way `keccak256(abi.encodePacked(addr))` does,
///         without going through the ABI encoder. Cheaper bytecode at every call site.
/// @dev `mstore` writes the address into the lower 20 bytes of slot 0 (with 12 leading
///      zero bytes of padding). We then hash only the address bytes by reading 20 bytes
///      starting at offset 12, which matches `abi.encodePacked(addr)` exactly.
function hashAddress(address input) pure returns (bytes32 hash) {
    assembly ("memory-safe") {
        mstore(0, input)
        hash := keccak256(12, 20)
    }
}

dependencies/onchain-id-develop/contracts/libraries/KeyPurposes.sol

// SPDX-License-Identifier: GPL-3.0
//
// ONCHAINID Smart Contracts
// Digital identities for the T-REX ecosystem.
//
// Copyright (C) 2026 Digital Asset Operational Services ISAC Ltd. ("T-REX Network")
//
// This file is part of the ONCHAINID smart contract suite.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

pragma solidity ^0.8.27;

/// @title KeyPurposes
/// @notice Constants for Key Purposes
library KeyPurposes {

    /// @dev 1: MANAGEMENT keys, which can manage the identity
    uint256 internal constant MANAGEMENT = 1;

    /// @dev 2: ACTION keys, which perform actions in this identities name (signing, logins, transactions, etc.)
    uint256 internal constant ACTION = 2;

    /// @dev 3: CLAIM signer keys, used to sign claims on other identities which need to be revokable.
    uint256 internal constant CLAIM_SIGNER = 3;

    /// @dev 4: ENCRYPTION keys, used to encrypt data e.g. hold in claims.
    uint256 internal constant ENCRYPTION = 4;

    /// @dev 5: CLAIM_ADDER key, can add claims but cannot remove them.
    uint256 internal constant CLAIM_ADDER = 5;

    /// @dev 6: PROPOSER keys can queue executions on the identity but cannot auto-run
    ///      or self-approve them. Used to raise the floor on who can push entries onto
    ///      the execution queue without expanding any auto-approval rule.
    uint256 internal constant PROPOSER = 6;

}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "dependencies/trex-develop/contracts/token/TokenGuardsLib.sol": {
      "TokenGuardsLib": "0xC8E48bf2154d6f2aABC98B0a4743D0d3f327bf58"
    },
    "dependencies/trex-develop/contracts/token/TokenLedgerLib.sol": {
      "TokenLedgerLib": "0x543F036f6812c5a799C818465CE8760bFEdBBf0B"
    },
    "dependencies/trex-develop/contracts/token/TokenRecoveryLib.sol": {
      "TokenRecoveryLib": "0x5231A9f48994FBED949f051a53477349DCFBF9B4"
    },
    "dependencies/trex-develop/contracts/interop/TREXMessagingLib.sol": {
      "TREXMessagingLib": "0x4142e2230413f167Ab98D8A3DB5dFCe2A475c5c9"
    },
    "dependencies/trex-develop/contracts/token/TokenDelegationLib.sol": {
      "TokenDelegationLib": "0x52d24426b844737Fc5fdF704Bf68346CbB4F45BE"
    },
    "dependencies/trex-develop/contracts/compliance/modular/ModuleSetLib.sol": {
      "ModuleSetLib": "0xF674215e1FC78303C49960F9c0129A34f514900B"
    },
    "dependencies/trex-develop/contracts/compliance/modular/TransferValidationLib.sol": {
      "TransferValidationLib": "0xc49275Bea16629C86bF4636bf4bfB609102078d0"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@chainlink/=../dependencies/smartcontractkit-chainlink-evm-1.5.0/",
    "@dino/=../",
    "@createx/=../dependencies/createx-v1.0.0/",
    "@erc3643org/erc-3643/=../dependencies/erc3643org-4.2.0-beta1/",
    "@fee-collector/=../dependencies/FeeCollector-dev/",
    "@forge-std/=dependencies/forge-std-v1.14.0/",
    "@onchain-id/solidity/=dependencies/onchain-id-develop/",
    "@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
    "@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.7.0/",
    "@trex/=dependencies/trex-develop/",
    "@openzeppelin-contracts-5.7.0/=dependencies/@openzeppelin-contracts-5.7.0/",
    "@openzeppelin-contracts-upgradeable-5.7.0/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
    "@openzeppelin/accounts/=dependencies/onchain-id-develop/dependencies/@openzeppelin-accounts-0.0.0-4ceb836d/packages/contracts/src/",
    "forge-std-v1.14.0/=dependencies/forge-std-v1.14.0/src/",
    "forge-std/=dependencies/onchain-id-develop/dependencies/forge-std-v1.14.0/src/",
    "onchain-id-develop/=dependencies/onchain-id-develop/",
    "trex-develop/=dependencies/trex-develop/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.