TransferWithAuthorization

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

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

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

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

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

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

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

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

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

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

interface IFeeGateway {
    function payAndPass(address user, bytes32 nonce) external payable;
}

interface IERC20WithAuthorization is IERC20 {
    /**
     * @dev EIP-3009: Transfer with authorization.
     */
    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validBefore,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

/**
 * @title ShadowSettlement
 * @dev Dark tx settlement router using commitment-nullifier scheme.
 * Agents generate commitments/nullifiers off-chain via SDK (Poseidon-origin hashes), contract validates on-chain.
 * Supports native ETH, ERC20 (e.g. USDC for x402), ERC721 (e.g. NFTs, LP tokens).
 * x402: Integrates EIP-3009 with on-chain sig validation for gasless pulls.
 */

contract ShadowSettlement is ReentrancyGuard, Ownable {
    IFeeGateway public immutable FEE_GATEWAY = IFeeGateway(0x08Db140854AAb90463f6B61eB6F346C29BFB02EA);

    // Global nullifier set (prevents double-spends across assets)
    mapping(bytes32 => bool) public nullifiers;

    // Commitments storage (agent => commitment => spent flag)
    mapping(address => mapping(bytes32 => bool)) public commitments;

    // x402 nonces (per-user, to prevent replay)
    mapping(address => mapping(uint256 => bool)) public usedNonces;

    event ShieldedTransfer(
        address indexed sender,
        address indexed asset,
        uint256 indexed assetType, // 0: native, 1: ERC20, 2: ERC721
        address recipient,
        uint256 amountOrId,
        bytes32 commitment,
        bytes32 nullifier
    );
    event X402Executed(address indexed sender, address indexed recipient, address token, uint256 amount, bytes32 authorization);
    event FeePaidAndPassed(bytes32 nonce);
    event NullifierSpent(bytes32 indexed nullifier, address indexed spender);

    enum AssetType { Native, ERC20, ERC721 }

    constructor() Ownable(msg.sender) {}

    /**
     * @dev Shielded transfer: Agents submit off-chain-generated commitment; nullifier checked on spend.
     * Off-chain: SDK computes commitment = Poseidon(recipient + amount + secret), nullifier = Poseidon(sender + secret).
     * On-chain: Stores commitment, executes transfer if valid; reveal nullifier later via spendNullifier.
     * @param assetType Asset type.
     * @param asset Token address (0x0 for native).
     * @param amountOrId Amount/tokenId.
     * @param recipient Recipient (public, but concealed in commitment off-chain).
     * @param commitment Off-chain hash (proves validity without reveal).
     * @param nonce Fee pass.
     */
    function shieldedTransfer(
        AssetType assetType,
        address asset,
        uint256 amountOrId,
        address recipient,
        bytes32 commitment,
        bytes32 nonce
    ) external payable nonReentrant {
        // Pay fee
        FEE_GATEWAY.payAndPass{value: msg.value}(msg.sender, nonce);

        // Store commitment (agent asserts validity off-chain; disputes via Swarm/API)
        require(!commitments[msg.sender][commitment], "Commitment spent");
        commitments[msg.sender][commitment] = true;

        // Execute transfer (assumes pre-approval; nullifier enforces later)
        _executeShieldedTransfer(assetType, asset, amountOrId, recipient, msg.sender);

        emit ShieldedTransfer(msg.sender, asset, uint8(assetType), recipient, amountOrId, commitment, bytes32(0)); // Nullifier revealed later
        emit FeePaidAndPassed(nonce);
    }

    /**
     * @dev Reveal and spend nullifier (post-settlement, to unlink).
     * Called by agent after transfer; prevents double-spend.
     * @param nullifier Off-chain hash (Poseidon(sender + secret)).
     */
    function spendNullifier(bytes32 nullifier) external {
        require(!nullifiers[nullifier], "Nullifier spent");
        nullifiers[nullifier] = true;
        emit NullifierSpent(nullifier, msg.sender);
    }

    /**
     * @dev x402 settlement: Full EIP-3009 with sig validation.
     * Off-chain: SDK signs msg = keccak256(abi.encodePacked(token, sender, spender=this, value=amount, validBefore, nonce, deadline)).
     * Validates signer == sender, nonce fresh, then executes authorized pull.
     * @param token ERC20 (e.g., USDC; must support EIP-3009).
     * @param amount.
     * @param recipient.
     * @param authorization EIP-3009 bytes: abi.encode(validBefore, v, r, s).
     * @param commitment. Off-chain hash.
     * @param nonce. Fee pass.
     */
    function executeX402Transfer(
        address token,
        uint256 amount,
        address recipient,
        bytes calldata authorization,
        bytes32 commitment,
        bytes32 nonce
    ) external payable nonReentrant {
        // Pay fee
        FEE_GATEWAY.payAndPass{value: msg.value}(msg.sender, nonce);

        // Store commitment
        require(!commitments[msg.sender][commitment], "Commitment spent");
        commitments[msg.sender][commitment] = true;

        // Full EIP-3009 decode and validation
        (uint256 validBefore, uint8 v, bytes32 r, bytes32 s) = abi.decode(authorization, (uint256, uint8, bytes32, bytes32));
        require(block.timestamp <= validBefore, "Authorization expired");

        // Compute auth hash (standard EIP-3009 domain separator; match SDK)
        bytes32 authHash = keccak256(abi.encodePacked(
            "\x19\x01", // EIP-712 prefix
            keccak256(abi.encode(token, msg.sender, address(this), amount, validBefore)),
            keccak256(abi.encodePacked(uint256(0x29fcb36a), block.chainid, address(this))) // Domain: name="TransferWithAuthorization", version=1, chainId
        ));
        address signer = ecrecover(authHash, v, r, s);
        require(signer == msg.sender, "Invalid signature");

        // Execute authorized transfer
        IERC20WithAuthorization(token).transferWithAuthorization(msg.sender, recipient, amount, validBefore, v, r, s);

        emit X402Executed(msg.sender, recipient, token, amount, keccak256(authorization));
        emit FeePaidAndPassed(nonce);
    }

    /**
     * @dev Internal execution (precise escrows optional; removed for simplicity as commitments suffice).
     */
    function _executeShieldedTransfer(
        AssetType assetType,
        address asset,
        uint256 amountOrId,
        address recipient,
        address sender
    ) internal {
        if (assetType == AssetType.Native) {
            payable(recipient).transfer(amountOrId);
        } else if (assetType == AssetType.ERC20) {
            IERC20(asset).transferFrom(sender, recipient, amountOrId);
        } else if (assetType == AssetType.ERC721) {
            IERC721(asset).safeTransferFrom(sender, recipient, amountOrId);
        } else {
            revert("Unsupported asset type");
        }
    }

    /**
     * @dev Owner invalidates invalid commitments (dispute resolution).
     */
    function invalidateCommitment(address user, bytes32 commitment) external onlyOwner {
        commitments[user][commitment] = false;
    }

    // Allow receiving ETH
    receive() external payable {}
}

Tags:
ERC20, ERC721, ERC165, Multisig, Non-Fungible, Upgradeable, Multi-Signature, Factory|addr:0xc88be2c2b0f2de79683df07bb4a80eeb7e5758f8|verified:true|block:23686090|tx:0x45db4609e226efef46e357c5d48366881f76ec0992c95072b2747dba16e119b7|first_check:1761820968

Submitted on: 2025-10-30 11:42:50

Comments

Log in to comment.

No comments yet.