Skip to content
Verified contractExactGPL-2.0-or-later

MamoruGasPolicyV2

Address0xe58dad8b381ff93a28aa2a43de80acb96f535c7b
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,328,646
Creation transaction
0xec225eba33…1f43830945

src/MamoruGasPolicyV2.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import {ConfigIdV4, PackedUserOperationV4} from "./SmartSessionTypes.sol";
import {MamoruV4Chains} from "./MamoruV4Chains.sol";

/**
 * @title MamoruGasPolicyV2 (spec 010 I6, otto/mamoru#292). Not deployed.
 * @notice The only userOp policy of a Mamoru V4 session. MamoruGasPolicy's per-op caps (T6 L-1, T7: priority fee, max
 * fee, every gas limit) plus a per-account GAS BUCKET per window and a cumulative GAS_REVIEW threshold, so a leaked
 * session key cannot drain the Safe's gas reserve with valid no-op or tiny userOps (r1 P1-6, r4 P1).
 *
 * SmartSession calls a userOp policy only at validation and has no settlement callback (r5 P1), so the policy cannot
 * see the gas an op actually paid. It charges each op CONSERVATIVELY at validation, from its capped fields: the most the
 * EntryPoint v0.7 can take from the account for it,
 *   (callGasLimit + verificationGasLimit + preVerificationGas + paymasterVerificationGasLimit + paymasterPostOpGasLimit)
 *   x maxFeePerGas
 * (the prefund; actual gas, the 10 % unused-gas penalty and preVerificationGas are all inside it). An op that would
 * cross the bucket or the threshold is REJECTED (VALIDATION_FAILED, nothing written), so the charged total never passes
 * either. The charge is written at validation: an op that validates and then fails or reverts in execution keeps it
 * (conservative). A bundle that reverts as a whole reverts the charge with it, but then nothing was paid either.
 *
 * GAS_REVIEW is pinned per chain (MamoruV4Chains: 0.01 ETH on Base, 5 MON on Monad; any other chain 0, so every op is
 * refused: fail closed). Once the charges since the guardian's last `review(account)` would pass it, every op of the
 * account is refused until the guardian reviews it: a slow drain stops at GAS_REVIEW per chain. The guardian cannot
 * spend, enable or widen anything; it only resets the counter.
 *
 * State: per-op caps and bucket parameters per (ConfigId, account), written only by SmartSession from an
 * owner-authorized enable (`initializeWithMultiplexer`); the bucket and the counter per ACCOUNT, so two sessions of one
 * account share them. Both are written only by SmartSession (V1 let any caller write its own multiplexer slot; V2's
 * account-level state forbids that, as MamoruActionPolicyV3 does). Every mapping has the account as its LAST key, so
 * each slot is `keccak(account || x) + n`: storage associated with the sender under ERC-7562.
 */
contract MamoruGasPolicyV2 {
    uint256 internal constant VALIDATION_SUCCESS = 0;
    uint256 internal constant VALIDATION_FAILED = 1;
    uint32 public constant MIN_WINDOW = 1 hours;

    address public constant SMART_SESSION = 0x00000000002B0eCfbD0496EE71e01257dA0E37DE;
    /// Revoke-only watchdog key (the same as MamoruActionPolicyV4's): `review` only.
    address public immutable GUARDIAN;

    /// MamoruGasPolicy's Caps, then the paymaster's two limits together, the bucket per window (wei) and the window.
    struct Caps {
        uint64 maxPriorityFeePerGas;
        uint32 maxVerificationGasLimit;
        uint32 maxCallGasLimit;
        uint32 maxPreVerificationGas;
        uint64 maxFeePerGas;
        uint32 maxPaymasterGas;
        uint128 perWindow;
        uint32 window;
    }

    struct Bucket {
        uint128 debt; // wei charged and not yet refilled
        uint64 updatedAt;
    }

    mapping(ConfigIdV4 => mapping(address account => Caps)) internal _caps;
    mapping(address account => Bucket) internal _bucket;
    /// Wei charged since the guardian's last review (I6 GAS_REVIEW).
    mapping(address account => uint256) public chargedSinceReview;

    event PolicySet(ConfigIdV4 id, address multiplexer, address account);
    event Charged(address indexed account, uint256 charge);
    event Reviewed(address indexed account, uint256 charged);

    error PolicyNotInitialized(ConfigIdV4 id, address multiplexer, address account);
    error BadInit(uint256 field);
    error OnlySmartSession();
    error OnlyGuardian();

    constructor(address guardian) {
        GUARDIAN = guardian;
    }

    function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
        return interfaceID == 0x01ffc9a7 // IERC165
            || interfaceID == this.checkUserOpPolicy.selector // smartsessions IUserOpPolicy
            || interfaceID == this.initializeWithMultiplexer.selector; // smartsessions IPolicy
    }

    /// The GAS_REVIEW of this chain (0 off the table: every op refused).
    function gasReview() public view returns (uint256) {
        return MamoruV4Chains.byChainId(block.chainid).gasReview;
    }

    function initializeWithMultiplexer(address account, ConfigIdV4 configId, bytes calldata initData) external {
        if (msg.sender != SMART_SESSION) revert OnlySmartSession();
        Caps memory c = abi.decode(initData, (Caps));
        if (c.maxPriorityFeePerGas == 0 || c.maxVerificationGasLimit == 0 || c.maxCallGasLimit == 0) revert BadInit(1);
        if (c.maxPreVerificationGas == 0 || c.maxFeePerGas < c.maxPriorityFeePerGas) revert BadInit(2);
        // The bucket is what bounds the drain per window; the review threshold bounds it over time. A bucket above
        // the threshold would be meaningless, a zero one refuses everything.
        if (c.perWindow == 0 || c.perWindow > gasReview() || c.window < MIN_WINDOW) revert BadInit(3);
        _caps[configId][account] = c;
        emit PolicySet(configId, msg.sender, account);
    }

    function checkUserOpPolicy(ConfigIdV4 id, PackedUserOperationV4 calldata op) external returns (uint256) {
        if (msg.sender != SMART_SESSION) return VALIDATION_FAILED; // nobody else may charge an account's bucket
        Caps memory c = _caps[id][op.sender];
        if (c.maxVerificationGasLimit == 0) revert PolicyNotInitialized(id, msg.sender, op.sender);
        uint256 verificationGasLimit = uint256(op.accountGasLimits) >> 128;
        uint256 callGasLimit = uint128(uint256(op.accountGasLimits));
        uint256 maxPriorityFeePerGas = uint256(op.gasFees) >> 128;
        uint256 maxFeePerGas = uint128(uint256(op.gasFees));
        uint256 pmGas;
        if (op.paymasterAndData.length != 0) {
            // EntryPoint v0.7: paymaster (20) | paymasterVerificationGasLimit (16) | paymasterPostOpGasLimit (16) | data
            if (op.paymasterAndData.length < 52) return VALIDATION_FAILED;
            pmGas = uint256(uint128(bytes16(op.paymasterAndData[20:36]))) + uint256(uint128(bytes16(op.paymasterAndData[36:52])));
        }
        if (
            maxPriorityFeePerGas > c.maxPriorityFeePerGas || maxFeePerGas > c.maxFeePerGas
                || verificationGasLimit > c.maxVerificationGasLimit || callGasLimit > c.maxCallGasLimit
                || op.preVerificationGas > c.maxPreVerificationGas || pmGas > c.maxPaymasterGas
        ) return VALIDATION_FAILED;
        // I6 (r6): the most this op can cost the account, charged now.
        uint256 charge = (callGasLimit + verificationGasLimit + op.preVerificationGas + pmGas) * maxFeePerGas;
        uint256 debt = _debtNow(_bucket[op.sender], c) + charge;
        uint256 since = chargedSinceReview[op.sender] + charge;
        if (debt > c.perWindow || since > gasReview()) return VALIDATION_FAILED; // crossing ops are rejected
        _bucket[op.sender] = Bucket(uint128(debt), uint64(block.timestamp));
        chargedSinceReview[op.sender] = since;
        emit Charged(op.sender, charge);
        return VALIDATION_SUCCESS;
    }

    /// The guardian, after checking the account's gas ledger, resets the cumulative counter (the bucket keeps going).
    function review(address account) external {
        if (msg.sender != GUARDIAN) revert OnlyGuardian();
        emit Reviewed(account, chargedSinceReview[account]);
        chargedSinceReview[account] = 0;
    }

    // ---------------------------------------------------------------- views

    function capsOf(address account, ConfigIdV4 id) external view returns (Caps memory) {
        return _caps[id][account];
    }

    /// (bucket room now, room before the review threshold), in wei, for `account` under `id`.
    function gasLeft(address account, ConfigIdV4 id) external view returns (uint256 window, uint256 untilReview) {
        Caps memory c = _caps[id][account];
        uint256 d = _debtNow(_bucket[account], c);
        window = c.perWindow > d ? c.perWindow - d : 0;
        uint256 r = gasReview();
        untilReview = r > chargedSinceReview[account] ? r - chargedSinceReview[account] : 0;
    }

    /// The largest charge one op under `c` can make (its prefund at the capped price and limits).
    function maxCostPerOp(Caps memory c) public pure returns (uint256) {
        return uint256(c.maxFeePerGas)
            * (uint256(c.maxVerificationGasLimit) + c.maxCallGasLimit + c.maxPreVerificationGas + c.maxPaymasterGas);
    }

    function _debtNow(Bucket memory b, Caps memory c) internal view returns (uint256 d) {
        d = b.debt;
        if (d != 0 && block.timestamp > b.updatedAt) {
            uint256 refill = (uint256(c.perWindow) * (block.timestamp - b.updatedAt)) / c.window;
            d = refill >= d ? 0 : d - refill;
        }
        if (d > c.perWindow) d = c.perWindow; // a re-init with a smaller bucket carries at most a full one
    }
}

src/MamoruV4Chains.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

/**
 * @title MamoruV4Chains (spec 010 "Pinned in V4", otto/mamoru#292): the per-chain tuple, keyed by block.chainid.
 * @notice Compiled into the bytecode of MamoruActionPolicyV4 and MamoruGasPolicyV2, identical on every chain (no
 * constructor argument chooses it), so "the same address" means "the same table" everywhere. The registry never
 * supplies any of it: a chain or a token outside this table needs a new V4 (the optional owner signature).
 *
 * Every address below was checked against packages/registry/base.json and monad.json (the repo's pinned registries,
 * with their code hashes) and read on chain at the fork blocks of the tests (Base 53,140,000; Monad 116,980,000;
 * Ethereum 26,328,000, otto/mamoru#307):
 *  - Uniswap v3 factory, NonfungiblePositionManager, SwapRouter02: base.json / monad.json entries of those names.
 *  - Stables: native USDC (Circle) on both; Base's USDT entry (6 decimals, base.json "stable del bucket stables").
 *    All pinned stables have 6 decimals, so the account bucket counts them 1:1 as USD units (test asserts it).
 *  - Assets: WETH and cbBTC on Base, WMON on Monad (base.json / monad.json), WETH on Ethereum.
 *  - Wrapped native (`wrapped`, the only target native value may go to, #307): assets[0] on every chain, a WETH9-style
 *    `deposit()` / `withdraw(uint256)` (WETH on Base and Ethereum, WMON on Monad; each simulated on chain).
 *  - CCTP domains: MessageTransmitterV2.localDomain() of the canonical TokenMessengerV2's localMessageTransmitter
 *    (0x81D40F21...) = 6 on Base, 15 on Monad, 0 on Ethereum.
 *  - Ethereum (#307): Uniswap v3 factory 0x1F98431c..., NonfungiblePositionManager 0xC36442b4... and SwapRouter02
 *    0x68b34658... (both report that factory and WETH9 = 0xC02aaA39...), native USDC 0xA0b86991... (6 decimals,
 *    `burnLimitsPerMessage` 1e13 on the canonical messenger's localMinter). USDT is left out there: its burn limit is
 *    0, so CCTP refuses it anyway, and its non-standard `approve` is one less surface. No MetaMorpho factory: no vault.
 *  - MetaMorpho factories (Base only): v1.0 0xA9c3D3a3... (`isMetaMorpho` is true for gtUSDCp and steakUSDC, the
 *    vaults spec 004 measured) and v1.1 0xFf62A7c2...; both return MORPHO() = Morpho Blue 0xBBBBBbbB... Monad has no
 *    MetaMorpho factory in the repo's registry: no vault is admissible there. Aave's static aToken factory exposes no
 *    membership view the repo has verified (spec 010 T2): Aave vaults are not admissible on any chain.
 * Left out, because nothing in the repo pins them yet (each needs its own verification before a V4 lists it):
 * Arbitrum, Optimism, Unichain. A route to one of them can be queued in the registry but V4 refuses it.
 */
library MamoruV4Chains {
    uint256 internal constant BASE = 8453;
    uint256 internal constant MONAD = 143;
    uint256 internal constant ETHEREUM = 1;

    /// The gas caps a remote session on this chain carries (MamoruGasPolicyV2.Caps, same field order).
    struct GasCaps {
        uint64 maxPriorityFeePerGas;
        uint32 maxVerificationGasLimit;
        uint32 maxCallGasLimit;
        uint32 maxPreVerificationGas;
        uint64 maxFeePerGas;
        uint32 maxPaymasterGas;
        uint128 perWindow; // wei of gas bucket per window
        uint32 window;
    }

    struct Chain {
        uint256 chainId; // 0 = not in the table
        uint32 domain; // CCTP domain
        address factory;
        address npm;
        address router;
        address[2] stables; // address(0) = unused slot
        address[2] assets;
        address wrapped; // WETH9-style wrapped native: the only target V4 lets native value reach (#307)
        address[2] vaultFactories; // MetaMorpho factories (isMetaMorpho)
        uint256 gasReview; // MamoruGasPolicyV2 GAS_REVIEW, wei
        GasCaps remoteCaps; // the gas policy init of a remote session on this chain
    }

    function byChainId(uint256 chainId) internal pure returns (Chain memory c) {
        if (chainId == BASE) {
            c.chainId = BASE;
            c.domain = 6;
            c.factory = 0x33128a8fC17869897dcE68Ed026d694621f6FDfD;
            c.npm = 0x03a520b32C04BF3bEEf7BEb72E919cf822Ed34f1;
            c.router = 0x2626664c2603336E57B271c5C0b26F421741e481;
            c.stables = [0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913, 0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2];
            c.assets = [0x4200000000000000000000000000000000000006, 0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf];
            c.wrapped = 0x4200000000000000000000000000000000000006;
            c.vaultFactories = [0xA9c3D3a366466Fa809d1Ae982Fb2c46E5fC41101, 0xFf62A7c278C62eD665133147129245053Bbf5918];
            c.gasReview = 0.01 ether;
            // packages/policy V4_GAS_CAPS (0.01 gwei priority, 3M / 2M / 200k, 0.1 gwei), bucket 0.002 ETH a day.
            c.remoteCaps = GasCaps(10_000_000, 3_000_000, 2_000_000, 200_000, 100_000_000, 0, 0.002 ether, 1 days);
        } else if (chainId == MONAD) {
            c.chainId = MONAD;
            c.domain = 15;
            c.factory = 0x204FAca1764B154221e35c0d20aBb3c525710498;
            c.npm = 0x7197E214c0b767cFB76Fb734ab638E2c192F4E53;
            c.router = 0xfE31F71C1b106EAc32F1A19239c9a9A72ddfb900;
            c.stables = [0x754704Bc059F8C67012fEd69BC8A327a5aafb603, address(0)];
            c.assets = [0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A, address(0)];
            c.wrapped = 0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A;
            c.gasReview = 5 ether;
            // packages/policy MONAD_GAS_CAPS (1 gwei priority, 3M / 2M / 200k, 1,000 gwei), bucket 1 MON a day.
            c.remoteCaps = GasCaps(1_000_000_000, 3_000_000, 2_000_000, 200_000, 1_000_000_000_000, 0, 1 ether, 1 days);
        } else if (chainId == ETHEREUM) {
            c.chainId = ETHEREUM;
            c.domain = 0;
            c.factory = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
            c.npm = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88;
            c.router = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45;
            c.stables = [0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, address(0)];
            c.assets = [0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(0)];
            c.wrapped = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
            // L1 gas: 0.1 gwei priority, 3M / 2M / 200k, 5 gwei max fee; a bucket of 0.01 ETH a day (a few ops at
            // today's ~0.3 gwei), and GAS_REVIEW 0.02 ETH. Ethereum is a chain where funds arrive and leave, not one
            // the engine trades on every hour.
            c.gasReview = 0.02 ether;
            c.remoteCaps = GasCaps(100_000_000, 3_000_000, 2_000_000, 200_000, 5_000_000_000, 0, 0.01 ether, 1 days);
        }
    }

    /// The chain id of a CCTP domain in the table, 0 when it is not in it. CCTP domain 0 is Ethereum: never a "no
    /// domain" sentinel here (#307).
    function chainOf(uint32 domain) internal pure returns (uint256) {
        return domain == 6 ? BASE : domain == 15 ? MONAD : domain == 0 ? ETHEREUM : 0;
    }

    function byDomain(uint32 domain) internal pure returns (Chain memory) {
        return byChainId(chainOf(domain)); // byChainId(0) is the empty entry
    }

    function isStable(Chain memory c, address t) internal pure returns (bool) {
        return t != address(0) && (t == c.stables[0] || t == c.stables[1]);
    }

    function isPinned(Chain memory c, address t) internal pure returns (bool) {
        return isStable(c, t) || (t != address(0) && (t == c.assets[0] || t == c.assets[1]));
    }
}

src/SmartSessionTypes.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

/// SmartSession's types (erc7579/smartsessions DataTypes.sol, Sourcify exact match on Base for
/// 0x00000000002B0eCfbD0496EE71e01257dA0E37DE), as MamoruActionPolicyV4 encodes them for a remote Safe's setup
/// (spec 010 I4). Field order is the ABI: do not reorder.

/// SmartSession's policy id type. Every Mamoru policy file declares its own (importing one would pull in its compiler
/// profile, foundry.toml); they are the same bytes32.
type ConfigIdV4 is bytes32;

struct PolicyData {
    address policy;
    bytes initData;
}

struct ERC7739Context {
    bytes32 appDomainSeparator;
    string[] contentName;
}

struct ERC7739Data {
    ERC7739Context[] allowedERC7739Content;
    PolicyData[] erc1271Policies;
}

struct ActionData {
    bytes4 actionTargetSelector;
    address actionTarget;
    PolicyData[] actionPolicies;
}

struct Session {
    address sessionValidator;
    bytes sessionValidatorInitData;
    bytes32 salt;
    PolicyData[] userOpPolicies;
    ERC7739Data erc7739Policies;
    ActionData[] actions;
    bool permitERC4337Paymaster;
}

/// ERC-4337 v0.7 PackedUserOperation.
struct PackedUserOperationV4 {
    address sender;
    uint256 nonce;
    bytes initCode;
    bytes callData;
    bytes32 accountGasLimits; // verificationGasLimit (high 128) | callGasLimit (low 128)
    uint256 preVerificationGas;
    bytes32 gasFees; // maxPriorityFeePerGas (high 128) | maxFeePerGas (low 128)
    bytes paymasterAndData;
    bytes signature;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "forge-std/=lib/forge-std/src/",
    "v3-core/=lib/v3-core/contracts/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.