Skip to content
Verified contractExactMIT

PeniwalletStorage

Address0xd6fceb7328a6b24a2a17d3640d3875df636ffc3d
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,163,166
Creation transaction
0xf2d56a0cde…12dd89573a

contracts/multidex/peniwallet_storage.sol

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

import "../verifier.sol";
import "../interfaces/IPeniwalletStorage.sol";

/**
 * @title PeniwalletV8Storage
 * @notice Manages all state for Peniwallet delegate contract with EIP-712 signature verification
 * @dev Centralized storage for nonces, admins, fees, and spray tracking, inherits EIP-712 from verifier
 * @author Enhanced for EIP-7702
 */

contract PeniwalletStorage is EIP712Verifier, IPeniwalletStorage {
    // Keyed transaction nonces (ERC-4337 style replay protection). The signed 256-bit
    // `nonce` field is split as key = nonce >> 64 (uint192), seq = low 64 bits. Each
    // (eoa, key) lane is a strictly sequential counter, so lanes never block each other.
    // Key 0 is every interactive action and encodes exactly like the old flat counter.
    // A lane's seq is a uint64; incrementing past type(uint64).max reverts (checked math),
    // which makes a lane permanently unusable at 2^64 - 1 uses - unreachable in practice.
    mapping(address => mapping(uint192 => uint64)) public nonces;

    // Global admin.
    address public owner;

    // Protocol relay-authority public key. Permits signed by this key authorize a
    // relayer (the on-chain caller / fee collector) until an expiry. Relayers are thus
    // authorized off-chain — there is no per-chain relayer list to maintain. The owner
    // rotates this on key compromise; relaying fails closed while it is the zero address.
    address public relayerAuthority;

    // Spray replay tracking, keyed on the EIP-712 digest (not the raw signature
    // bytes) so replay protection does not depend on signature-encoding canonicalization.
    mapping(bytes32 => bool) public usedSpraySignatures;

    // ******************************************************************************
    // * ERRORS                                                                    *
    // ******************************************************************************

    error Unauthorized();
    error InvalidNonce();
    error SpraySignatureUsed();

    /// @notice A lane was skipped forward by one by its owner.
    event NonceCancelled(address indexed eoa, uint192 indexed key, uint64 newSeq);

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

    event RelayerAuthorityUpdated(address indexed previousAuthority, address indexed newAuthority);

    modifier onlyOwner() {
        if (msg.sender != owner) revert Unauthorized();
        _;
    }

    /// @param _owner Storage admin, and the initial relay-permit authority.
    /// @dev Taken as an ARGUMENT rather than from `msg.sender`. Under CREATE2
    ///      through a shared deployer, `msg.sender` here is the deployer
    ///      contract, which nobody controls — the storage would be permanently
    ///      unownable and the deploy script's own `setRelayerAuthority` and
    ///      `transferOwnership` calls would revert. This was the only contract
    ///      in the stack reading `msg.sender` for ownership; the other four
    ///      already take `_owner`.
    constructor(address _owner) {
        if (_owner == address(0)) revert Unauthorized();
        owner = _owner;
        relayerAuthority = _owner;
        emit OwnershipTransferred(address(0), _owner);
        emit RelayerAuthorityUpdated(address(0), _owner);
    }

    // ******************************************************************************
    // * NONCE MANAGEMENT + OWNER ADMIN                                             *
    // ******************************************************************************

    /// @notice Next nonce on key 0 (equals its seq, since key 0 << 64 == 0).
    function getNonce(address eoa) external view returns (uint256) {
        return nonces[eoa][0];
    }

    /// @notice Full nonce (key << 64 | seq) the next intent on `key` must sign.
    function getNonce(address eoa, uint192 key) external view returns (uint256) {
        return (uint256(key) << 64) | nonces[eoa][key];
    }

    /// @notice Skip the caller's next nonce on `key` (invalidates one signed-but-unsent intent).
    /// @dev msg.sender is the EOA itself (EIP-7702 delegate calling Storage directly), the same
    ///      identity the verify functions require as `from`.
    function cancelNonce(uint192 key) external {
        uint64 newSeq = nonces[msg.sender][key] + 1;
        nonces[msg.sender][key] = newSeq;
        emit NonceCancelled(msg.sender, key, newSeq);
    }

    /// @dev Consume `nonce` for `from`: key = nonce >> 64, seq = low 64 bits.
    function _useNonce(address from, uint256 nonce) internal {
        uint192 key = uint192(nonce >> 64);
        if (nonces[from][key] != uint64(nonce)) revert InvalidNonce();
        nonces[from][key]++;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert Unauthorized();
        emit OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }

    /// @notice Rotate the relay-authority key (the signer of RelayerPermits). Setting it
    ///         to the zero address disables relaying (fail-closed) until set again.
    function setRelayerAuthority(address newAuthority) external onlyOwner {
        emit RelayerAuthorityUpdated(relayerAuthority, newAuthority);
        relayerAuthority = newAuthority;
    }

    /// @notice True iff `signature` is a valid, unexpired RelayerPermit for `relayer`
    ///         signed by the current `relayerAuthority`. The delegate calls this with
    ///         relayer = the external caller (msg.sender) to gate who may relay/collect
    ///         the fee, without any on-chain relayer list.
    function verifyRelayerPermit(address relayer, uint256 expiry, bytes calldata signature)
        external
        view
        returns (bool)
    {
        address authority = relayerAuthority;
        if (authority == address(0)) return false; // fail closed when unconfigured
        if (block.timestamp > expiry) return false; // permit expired
        if (signature.length != 65) return false; // missing/malformed permit → unauthorized
        RelayerPermit memory p = RelayerPermit({relayer: relayer, expiry: expiry});
        return _recoverRelayerPermit(p, signature) == authority;
    }

    // ******************************************************************************
    // * SIGNATURE VERIFICATION FUNCTIONS                                          *
    // ******************************************************************************

    /**
     * @notice Verify transfer transaction signature using inherited EIP-712
     * @param token Token address
     * @param from Sender address
     * @param to Recipient address
     * @param amount Transfer amount
     * @param nonce Transaction nonce
     * @param deadline Transaction deadline
     * @param signature EIP-712 signature
     * @return bool True if signature is valid
     */
    function verifyTransferSignature(
        address token,
        address from,
        address to,
        uint256 amount,
        uint256 fee,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) external returns (bool) {
        if (msg.sender != from) revert Unauthorized();
        TransferTransaction memory txn = TransferTransaction({
            token: token, from: from, to: to, amount: amount, fee: fee, nonce: nonce, deadline: deadline
        });

        bool verified = verifyTransfer(txn, signature);

        if (verified) {
            _useNonce(from, nonce);

            return true;
        }
        return false;
    }

    /**
     * @notice Verify swap transaction signature using inherited EIP-712
     * @param tokenA Token A address
     * @param tokenB Token B address
     * @param from Sender address
     * @param amountA Amount of token A
     * @param amountB Amount of token B
     * @param nonce Transaction nonce
     * @param deadline Transaction deadline
     * @param signature EIP-712 signature
     * @return bool True if signature is valid
     */
    function verifySwapSignature(
        address tokenA,
        address tokenB,
        address from,
        address recipient,
        uint256 amountA,
        uint256 amountB,
        uint256 fee,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) external returns (bool) {
        if (msg.sender != from) revert Unauthorized();
        SwapTransaction memory txn = SwapTransaction({
            tokenA: tokenA,
            tokenB: tokenB,
            from: from,
            recipient: recipient,
            amountA: amountA,
            amountB: amountB,
            fee: fee,
            nonce: nonce,
            deadline: deadline
        });

        bool verified = verifySwap(txn, signature);
        if (verified) {
            _useNonce(from, nonce);

            return true;
        }
        return false;
    }

    /**
     * @notice Verify spray transaction signature using inherited EIP-712
     * @param token Token address
     * @param from Sender address
     * @param receivers Array of recipient addresses
     * @param amount Amount per recipient
     * @param code Spray code
     * @param signature EIP-712 signature
     * @return bool True if signature is valid
     */
    function verifySpraySignature(
        address token,
        address from,
        address[] calldata receivers,
        uint256 amount,
        uint256 fee,
        uint256 deadline,
        string calldata code,
        bytes calldata signature
    ) external returns (bool) {
        if (msg.sender != from) revert Unauthorized();

        SprayTransaction memory txn = SprayTransaction({
            token: token, from: from, receivers: receivers, amount: amount, fee: fee, deadline: deadline, code: code
        });

        (bool verified, bytes32 digest) = verifySpray(txn, signature);

        if (verified) {
            if (usedSpraySignatures[digest]) revert SpraySignatureUsed();
            usedSpraySignatures[digest] = true;
            return true;
        }
        return false;
    }
}

contracts/interfaces/IPeniwalletStorage.sol

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

interface IPeniwalletStorage {
    function verifyTransferSignature(
        address token,
        address from,
        address to,
        uint256 amount,
        uint256 fee,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) external returns (bool);

    function verifySwapSignature(
        address tokenA,
        address tokenB,
        address from,
        address recipient,
        uint256 amountA,
        uint256 amountB,
        uint256 fee,
        uint256 nonce,
        uint256 deadline,
        bytes calldata signature
    ) external returns (bool);

    function verifySpraySignature(
        address token,
        address from,
        address[] calldata receivers,
        uint256 amount,
        uint256 fee,
        uint256 deadline,
        string calldata code,
        bytes calldata signature
    ) external returns (bool);

    /// @notice Validate that `relayer` is authorized by an unexpired permit signed by the
    ///         protocol relay authority. Used to gate the external caller / fee collector.
    function verifyRelayerPermit(
        address relayer,
        uint256 expiry,
        bytes calldata signature
    ) external view returns (bool);
}

contracts/verifier.sol

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

/**
 * @title EIP712Verifier
 * @dev Verifies two independent EIP-712 signatures:
 *      1. the USER's signature over the app-facing transaction intent (signer == `from`); and
 *      2. a RelayerPermit signed by the protocol's relay AUTHORITY key, authorizing a
 *         specific relayer (the on-chain caller / fee collector) until an expiry. This
 *         replaces the old on-chain relayer allowlist: relayers are now authorized by
 *         off-chain permits, so there is no per-chain list to maintain.
 *      Recovery enforces canonical (low-s, v in {27,28}) encodings so a malleated
 *      signature cannot bypass signature-keyed replay guards (e.g. the spray guard).
 * @author geofferyj
 */
contract EIP712Verifier {
    // EIP-712 domain separator, cached at deploy for the deploy-time chainId. Reads stay
    // cheap on the normal path; after a chain split (chainid() changes) it is re-derived
    // live so signatures cannot replay onto the forked chain.
    bytes32 public DOMAIN_SEPARATOR;
    // Not immutable: PeniwalletStorage relies on type(...).runtimeCode for its on-chain
    // identity check, which is unavailable for contracts with immutables. Set once in the
    // constructor; the read is a single SLOAD on the hot path.
    uint256 private _cachedChainId;

    // secp256k1 order / 2 — the upper bound for a canonical (low-s) signature (EIP-2).
    uint256 private constant _HALF_N =
        0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    struct TransferTransaction {
        address token;
        address from;
        address to;
        uint256 amount;
        uint256 fee;
        uint256 nonce;
        uint256 deadline;
    }

    bytes32 public constant TransferTransaction_TYPEHASH =
        keccak256(
            "TransferTransaction(address token,address from,address to,uint256 amount,uint256 fee,uint256 nonce,uint256 deadline)"
        );

    struct SwapTransaction {
        address tokenA;
        address tokenB;
        address from;
        address recipient;
        uint256 amountA;
        uint256 amountB;
        uint256 fee;
        uint256 nonce;
        uint256 deadline;
    }

    bytes32 public constant SwapTransaction_TYPEHASH =
        keccak256(
            "SwapTransaction(address tokenA,address tokenB,address from,address recipient,uint256 amountA,uint256 amountB,uint256 fee,uint256 nonce,uint256 deadline)"
        );

    struct SprayTransaction {
        address token;
        address from;
        address[] receivers;
        uint256 amount;
        uint256 fee;
        uint256 deadline;
        string code;
    }

    bytes32 public constant SprayTransaction_TYPEHASH =
        keccak256(
            "SprayTransaction(address token,address from,address[] receivers,uint256 amount,uint256 fee,uint256 deadline,string code)"
        );

    // Signed by the protocol relay AUTHORITY key (see PeniwalletStorage.relayerAuthority)
    // to authorize `relayer` as the on-chain caller / fee collector until `expiry`. The
    // EIP-712 domain already binds chainId + verifyingContract, so a permit is scoped to
    // this chain's storage contract; `expiry` bounds how long a relayer stays authorized.
    struct RelayerPermit {
        address relayer;
        uint256 expiry;
    }

    bytes32 public constant RelayerPermit_TYPEHASH =
        keccak256("RelayerPermit(address relayer,uint256 expiry)");

    constructor() {
        _cachedChainId = block.chainid;
        DOMAIN_SEPARATOR = _buildDomainSeparator();
    }

    /// @dev Build the domain separator against the LIVE chainId and this address.
    function _buildDomainSeparator() private view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256(
                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                    ),
                    keccak256(bytes("Peniwallet")), // Contract name
                    keccak256(bytes("1")), // Version
                    block.chainid, // Chain ID
                    address(this) // Contract address
                )
            );
    }

    /// @dev The cached separator on the original chain; re-derived if the chainId changed
    ///      (post-fork), so a signature for the original chain does not verify on the fork.
    function _domainSeparatorV4() internal view returns (bytes32) {
        return
            block.chainid == _cachedChainId
                ? DOMAIN_SEPARATOR
                : _buildDomainSeparator();
    }

    // ─────────────────────────────────────────────────────────────────────
    // USER signature verification (signer must equal `from`)
    // ─────────────────────────────────────────────────────────────────────

    function verifyTransfer(
        TransferTransaction memory t,
        bytes memory signature
    ) internal view returns (bool) {
        bytes32 structHash = keccak256(
            abi.encode(
                TransferTransaction_TYPEHASH,
                t.token,
                t.from,
                t.to,
                t.amount,
                t.fee,
                t.nonce,
                t.deadline
            )
        );
        return _getSigner(signature, structHash) == t.from;
    }

    function verifySwap(
        SwapTransaction memory t,
        bytes memory signature
    ) internal view returns (bool) {
        bytes32 structHash = keccak256(
            abi.encode(
                SwapTransaction_TYPEHASH,
                t.tokenA,
                t.tokenB,
                t.from,
                t.recipient,
                t.amountA,
                t.amountB,
                t.fee,
                t.nonce,
                t.deadline
            )
        );
        return _getSigner(signature, structHash) == t.from;
    }

    /// @dev Returns whether the signature is the user's, plus the EIP-712 digest.
    ///      The digest (not the raw signature bytes) is the canonical replay key for
    ///      the nonce-less spray path, so replay protection is independent of
    ///      signature encoding.
    function verifySpray(
        SprayTransaction memory t,
        bytes memory signature
    ) internal view returns (bool valid, bytes32 digest) {
        bytes32 structHash = keccak256(
            abi.encode(
                SprayTransaction_TYPEHASH,
                t.token,
                t.from,
                keccak256(abi.encodePacked(t.receivers)),
                t.amount,
                t.fee,
                t.deadline,
                keccak256(abi.encodePacked(t.code))
            )
        );
        digest = _typedDataHash(structHash);
        valid = _recover(digest, signature) == t.from;
    }

    /// @dev Recover the signer of a RelayerPermit. The caller (storage) compares this to
    ///      its configured `relayerAuthority` and enforces `expiry`. Chain/contract scope
    ///      comes from the EIP-712 domain separator.
    function _recoverRelayerPermit(
        RelayerPermit memory p,
        bytes memory signature
    ) internal view returns (address) {
        bytes32 structHash = keccak256(
            abi.encode(RelayerPermit_TYPEHASH, p.relayer, p.expiry)
        );
        return _recover(_typedDataHash(structHash), signature);
    }

    // ─────────────────────────────────────────────────────────────────────
    // ECDSA recovery with canonical-signature enforcement (EIP-2 low-s + v∈{27,28})
    // ─────────────────────────────────────────────────────────────────────

    function _getSigner(
        bytes memory signature,
        bytes32 structHash
    ) private view returns (address) {
        return _recover(_typedDataHash(structHash), signature);
    }

    /// @dev EIP-712 typed-data digest for a given struct hash.
    function _typedDataHash(bytes32 structHash) private view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)
            );
    }

    /// @dev ecrecover with canonical-signature enforcement (EIP-2 low-s + v∈{27,28}).
    function _recover(
        bytes32 messageHash,
        bytes memory signature
    ) private pure returns (address) {
        require(signature.length == 65, "Invalid signature: length mismatch");

        uint8 v;
        bytes32 r;
        bytes32 s;
        assembly {
            r := mload(add(signature, 32))
            s := mload(add(signature, 64))
            v := byte(0, mload(add(signature, 96)))
        }

        // Reject malleable (high-s / non-canonical v) signatures so a second valid
        // encoding of the same signature cannot bypass signature-keyed replay guards.
        require(uint256(s) <= _HALF_N, "Invalid signature: high s");
        require(v == 27 || v == 28, "Invalid signature: bad v");

        address signer = ecrecover(messageHash, v, r, s);
        require(signer != address(0), "Invalid signature: zero address");
        return signer;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.