Перейти к содержимому
Проверенный контрактТочноеUNLICENSED

YieldyCallPolicy

Адрес0xc06e99e39104dd6bb31e61b56bbdbe9b2f93e7c6
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.26

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.26+commit.8a97fa7a
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Лицензия
UNLICENSED
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 407 537
Транзакция создания
0x1194e79baa…26990fecfb

50 файлов

Исходный код большой: показывается один файл. Выберите файл в списке.

src/YieldyCallPolicy.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC4337Utils} from "@openzeppelin/contracts/account/utils/ERC4337Utils.sol";
import {IKernelAccount, IPolicy, PackedUserOperation} from "./interfaces/IPolicy.sol";
import {KernelAccount} from "./KernelAccount.sol";
import {Logic} from "./Logic.sol";
import {StrategyManager} from "./StrategyManager.sol";

/// @notice The session key's rules, in code. A Kernel v3.1 permission policy that allows the
/// session key only the calls the backend needs, so a stolen session key can move funds only
/// between the owner's wallet, the owner's accounts and the front door, plus the paymaster's
/// charge for gas, which it takes from the account's tokens through the `approve` allowed here.
/// Two more outflows go with those calls by design: Yieldy's fees to the treasury (`collectFee`),
/// and on a Morpho Vault V2 exit its redeem cannot pay, the vault's forced-exit penalty on the
/// part forced (up to 2%, sized by the amount the key picks; `minOutput` may be zero;
/// AUDIT_PACKAGE §4).
/// The wallet is the one stored at install: after a root-key change it is still the old wallet,
/// until the session is replaced (AUDIT_PACKAGE §5).
///
/// The rules are code, shared by every account. Per account it stores only the owner's wallet,
/// the account's plan and the owner's two other accounts: three slots under
/// `configs[permissionId][account]`. The install checks that the account is the wallet's Kernel
/// account for the plan and derives the two others from the wallet (`KernelAccount`, Logic's
/// rule), so the install data names no address the owner does not control. Each slot is
/// `keccak(account ‖ x) + n`, storage associated with the account under ERC-7562. Bundlers accept
/// it in validation; in the operation that creates the account, only with a staked factory, so
/// the first operation's initCode goes through ZeroDev's staked meta factory. In the
/// token paymaster's ERC-20 mode only the paymaster operator's bundlers include the operations
/// (its unstaked post-op). The account is `msg.sender`;
/// StrategyManager, Logic and the paymaster are immutables. One deployment per chain and per
/// front door, Logic and paymaster.
///
/// Kernel calls, all with `msg.sender` = the account:
/// - `onInstall(bytes32(permissionId) ‖ wallet ‖ plan)` when the session is enabled. The owner's
///   enable signature covers these bytes.
/// - `checkUserOpPolicy(bytes32(permissionId), op)` for every operation of the session. A revert
///   refuses the operation.
/// - `onUninstall(bytes32(permissionId) ‖ anything)` from `uninstallValidation`. Kernel ignores
///   its result.
/// An account with nothing stored is allowed nothing: before the install and after the uninstall
/// (Kernel's `uninstallModule` can remove the policy and leave the session in place).
///
/// Kernel's flags decide whether it asks the policy at all, so the policy checks them itself:
/// its own entry must carry no flag (`SKIP_USEROP` would skip every rule here,
/// `SKIP_SIGNATURE` this policy's signature refusal), checked at the install; the permission
/// must carry `SKIP_SIGNATURE`, so Kernel refuses every signature of the session key. Kernel
/// writes the permission's flag after the policies' `onInstall`, so it is checked at every
/// operation. Both are reads of the account's own storage.
///
/// An operation must name the paymaster as its paymaster, so the account's ETH never pays its
/// gas, and must be `execute(mode, executionCalldata)` with call type single or batch, exec type
/// default, and no ETH on any call. Every call must be one of:
/// 1. `act(routeId, amount, minOutput, params)` on StrategyManager, `params` right after the head,
///    at least one word long, and its first word the account, a sibling or zero;
/// 2. `collectFee(routeId, params)` on StrategyManager;
/// 3. `setPlan(plan)` on Logic, with the account's plan;
/// 4. `approve(spender, amount)` on any token, spender StrategyManager or the paymaster;
/// 5. `transfer(to, amount)` on any token, `to` the wallet, the account or a sibling;
/// 6. `permit(owner, spender, …)` on any token, owner the wallet and spender the account;
/// 7. `transferFrom(from, to, amount)` on any token, from the wallet and to the account;
/// 8. `uninstallValidation(vId, …)` on the account itself, `vId` this session's own;
/// 9. `enroll(entryRouteId)` on Logic: counts receipts the account already holds, such as an
///    import pulled from the wallet with rules 6 and 7. Logic checks the rest.
/// Arguments are compared as raw ABI words: an address word with dirty upper bits never matches.
contract YieldyCallPolicy is IPolicy {
    error ZeroAddress();
    error InvalidInstallData();
    error NotInstalled();
    error PaymasterRequired();
    error NotExecute();
    error CallTypeNotAllowed(bytes1 callType);
    error ExecTypeNotAllowed(bytes1 execType);
    error ValueNotAllowed();
    error DirtyTarget();
    error SelectorNotAllowed(bytes4 selector);
    error TargetNotAllowed(bytes4 selector, address target);
    error ArgumentNotAllowed(bytes4 selector, uint256 word);
    error PolicyFlagNotAllowed(bytes2 flag);
    error SignaturesNotRefused(bytes2 permissionFlag);

    uint256 internal constant MODULE_TYPE_POLICY = 5;
    /// @dev Kernel v3.1's `SKIP_SIGNATURE` flag: on a permission, Kernel refuses its signatures.
    bytes2 internal constant SKIP_SIGNATURE = 0x0002;

    bytes1 internal constant CALLTYPE_SINGLE = 0x00;
    bytes1 internal constant CALLTYPE_BATCH = 0x01;
    bytes1 internal constant EXECTYPE_DEFAULT = 0x00;

    bytes4 internal constant EXECUTE = IKernelAccount.execute.selector;
    bytes4 internal constant ACT = StrategyManager.act.selector;
    bytes4 internal constant COLLECT_FEE = StrategyManager.collectFee.selector;
    bytes4 internal constant SET_PLAN = Logic.setPlan.selector;
    bytes4 internal constant ENROLL = Logic.enroll.selector;
    bytes4 internal constant APPROVE = IERC20.approve.selector;
    bytes4 internal constant TRANSFER = IERC20.transfer.selector;
    bytes4 internal constant PERMIT = IERC20Permit.permit.selector;
    bytes4 internal constant TRANSFER_FROM = IERC20.transferFrom.selector;
    bytes4 internal constant UNINSTALL_VALIDATION = IKernelAccount.uninstallValidation.selector;

    /// @dev Kernel's validation type for a permission: the first byte of its bytes21 validation id.
    bytes32 internal constant VALIDATION_TYPE_PERMISSION = bytes32(bytes1(0x02));
    /// @dev `act`'s `params` offset when it directly follows the four head words.
    uint256 internal constant ACT_PARAMS_OFFSET = 0x80;
    /// @dev Install data: the permission id word, then the wallet (20 bytes) and the plan (one byte).
    uint256 internal constant INSTALL_DATA_LENGTH = 32 + 20 + 1;

    /// @dev Slot 0: wallet and plan; slot 1: sibling1; slot 2: sibling2.
    struct Config {
        address wallet;
        uint8 plan;
        address sibling1;
        address sibling2;
    }

    address public immutable strategyManager;
    address public immutable logic;
    address public immutable paymaster;

    /// @dev The account is the inner key, so every slot is the account's own storage (ERC-7562).
    mapping(bytes32 permissionId => mapping(address account => Config)) internal _configs;

    constructor(address strategyManager_, address logic_, address paymaster_) {
        if (strategyManager_ == address(0) || logic_ == address(0) || paymaster_ == address(0)) {
            revert ZeroAddress();
        }
        strategyManager = strategyManager_;
        logic = logic_;
        paymaster = paymaster_;
    }

    // ---------------------------------------------------------------------
    // Module
    // ---------------------------------------------------------------------

    function isModuleType(uint256 moduleTypeId) external pure returns (bool) {
        return moduleTypeId == MODULE_TYPE_POLICY;
    }

    /// @dev Kernel v3.1 never calls this. An install counter would cost one more new slot at every
    /// install, so none is kept and the answer is always false.
    function isInitialized(address) external pure returns (bool) {
        return false;
    }

    /// @notice Writes the account's three slots, over any earlier ones. Kernel v3.1 enables a
    /// permission id once: a second enable of the same id, even after a revoke, fails with
    /// `InvalidNonce` unless the root key first raises the account's validation nonce. The
    /// account must be the wallet's account for the plan (1, 2 or 3); the siblings are the
    /// wallet's accounts for the two other plans, in plan order.
    function onInstall(bytes calldata data) external payable {
        if (data.length != INSTALL_DATA_LENGTH) revert InvalidInstallData();
        address wallet = address(bytes20(data[32:52]));
        uint8 plan = uint8(data[52]);
        if (wallet == address(0) || plan == 0 || plan > 3) revert InvalidInstallData();
        bytes memory init = KernelAccount.init(wallet);
        if (KernelAccount.account(init, wallet, plan) != msg.sender) revert InvalidInstallData();
        _requireOwnFlagClear(bytes4(data[0:4]));
        _configs[bytes32(data[0:32])][msg.sender] = Config({
            wallet: wallet,
            plan: plan,
            sibling1: KernelAccount.account(init, wallet, plan == 1 ? 2 : 1),
            sibling2: KernelAccount.account(init, wallet, plan == 3 ? 2 : 3)
        });
    }

    /// @dev Kernel stores the permission's policy entries before it calls `onInstall`. Every
    /// entry of this policy must carry no flag, and there must be one.
    function _requireOwnFlagClear(bytes4 permissionId) private view {
        bytes22[] memory entries = IKernelAccount(msg.sender).permissionConfig(permissionId).policyData;
        bool found;
        for (uint256 i; i < entries.length; ++i) {
            if (address(bytes20(entries[i] << 16)) != address(this)) continue;
            if (bytes2(entries[i]) != 0) revert PolicyFlagNotAllowed(bytes2(entries[i]));
            found = true;
        }
        if (!found) revert PolicyFlagNotAllowed(0xffff);
    }

    /// @notice Clears the account's three slots. Kernel ignores the result and the rest of `data`.
    function onUninstall(bytes calldata data) external payable {
        delete _configs[bytes32(data[0:32])][msg.sender];
    }

    /// @notice The stored configuration of `account` under `permissionId`.
    function configOf(bytes32 permissionId, address account) external view returns (Config memory) {
        return _configs[permissionId][account];
    }

    // ---------------------------------------------------------------------
    // Policy
    // ---------------------------------------------------------------------

    /// @notice Always refuses. The permission carries Kernel's `SKIP_SIGNATURE` (checked at every
    /// operation), so Kernel refuses the session key's signatures before it asks a policy; this
    /// answer refuses them too if it is asked.
    function checkSignaturePolicy(bytes32, address, bytes32, bytes calldata) external pure returns (uint256) {
        return 1;
    }

    /// @notice Returns 0 (allowed, no time window) or reverts. The paymaster must pay the gas:
    /// without it the EntryPoint takes the prefund from the account's ETH and pays it to whoever
    /// bundles the operation, at the gas price the session key signed. The calls are decoded the
    /// way Kernel's own `execute` decodes them: offsets from the same bases, and every slice
    /// bounds-checked against the declared lengths. So the calls checked here are exactly the
    /// calls Kernel would run.
    function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp) external payable returns (uint256) {
        Config storage config = _configs[id][msg.sender];
        if (config.wallet == address(0)) revert NotInstalled();
        // Kernel's key is the 4-byte permission id, left-aligned in the word: the cast keeps it.
        // forge-lint: disable-next-line(unsafe-typecast)
        bytes2 permissionFlag = IKernelAccount(msg.sender).permissionConfig(bytes4(id)).permissionFlag;
        if (permissionFlag & SKIP_SIGNATURE == 0) revert SignaturesNotRefused(permissionFlag);
        // The paymaster is the first 20 bytes. The EntryPoint reads an empty field as no paymaster
        // and refuses 1 to 51 bytes (AA93); OZ answers zero for both.
        if (ERC4337Utils.paymaster(userOp) != paymaster) revert PaymasterRequired();
        (bytes1 callType, bytes calldata execution) = _execution(userOp.callData);
        if (callType == CALLTYPE_SINGLE) {
            // abi.encodePacked(target, value, data), as Kernel's ExecLib.decodeSingle reads it.
            _checkCall(
                id, config, address(bytes20(execution[0:20])), uint256(bytes32(execution[20:52])), execution[52:]
            );
        } else if (callType == CALLTYPE_BATCH) {
            // abi.encode(Execution[]), Execution = (address target, uint256 value, bytes callData).
            uint256 arrayOffset = uint256(bytes32(execution[0:32]));
            uint256 count = uint256(bytes32(execution[arrayOffset:arrayOffset + 32]));
            bytes calldata heads = execution[arrayOffset + 32:];
            for (uint256 i; i < count; ++i) {
                _checkBatchItem(id, config, heads, i);
            }
        } else {
            revert CallTypeNotAllowed(callType);
        }
        return 0;
    }

    /// @dev `execute(bytes32 mode, bytes executionCalldata)`: the call type and the execution
    /// bytes. ABI offsets are relative to `callData[4:]`, as in Kernel's own `execute`.
    function _execution(bytes calldata callData) private pure returns (bytes1 callType, bytes calldata execution) {
        if (callData.length < 4 || bytes4(callData[0:4]) != EXECUTE) revert NotExecute();
        bytes calldata args = callData[4:];
        callType = args[0];
        bytes1 execType = args[1];
        if (execType != EXECTYPE_DEFAULT) revert ExecTypeNotAllowed(execType);
        uint256 offset = uint256(bytes32(args[32:64]));
        uint256 length = uint256(bytes32(args[offset:offset + 32]));
        execution = args[offset + 32:offset + 32 + length];
    }

    /// @dev Item `i` of an ABI-encoded Execution[] whose head words start at `heads`, read as
    /// Solidity reads `executions[i]` in Kernel's ExecLib: offsets relative to the head start.
    function _checkBatchItem(bytes32 id, Config storage config, bytes calldata heads, uint256 i) private view {
        bytes calldata item = heads[uint256(bytes32(heads[i * 32:i * 32 + 32])):];
        uint256 target = uint256(bytes32(item[0:32]));
        if (target >> 160 != 0) revert DirtyTarget();
        uint256 dataOffset = uint256(bytes32(item[64:96]));
        uint256 dataLength = uint256(bytes32(item[dataOffset:dataOffset + 32]));
        _checkCall(
            id,
            config,
            // The upper bits were checked clean just above.
            // forge-lint: disable-next-line(unsafe-typecast)
            address(uint160(target)),
            uint256(bytes32(item[32:64])),
            item[dataOffset + 32:dataOffset + 32 + dataLength]
        );
    }

    /// @dev One call against the nine rules. The free comparisons (the account, zero, the
    /// immutables) come before the stored values.
    function _checkCall(bytes32 id, Config storage config, address target, uint256 value, bytes calldata data)
        private
        view
    {
        if (value != 0) revert ValueNotAllowed();
        bytes4 selector = bytes4(data[0:4]);
        uint256 account = uint160(msg.sender);

        if (selector == APPROVE) {
            // approve(spender, amount) on any token: StrategyManager or the paymaster.
            uint256 spender = _word(data, 0);
            if (spender != uint160(strategyManager) && spender != uint160(paymaster)) {
                revert ArgumentNotAllowed(selector, spender);
            }
        } else if (selector == TRANSFER) {
            // transfer(to, amount) on any token: the account, the wallet or a sibling.
            uint256 to = _word(data, 0);
            if (
                to != account && to != uint160(config.wallet) && to != uint160(config.sibling1)
                    && to != uint160(config.sibling2)
            ) revert ArgumentNotAllowed(selector, to);
        } else if (selector == PERMIT || selector == TRANSFER_FROM) {
            // permit(owner = wallet, spender = account, …) and
            // transferFrom(from = wallet, to = account, amount) on any token.
            uint256 from = _word(data, 0);
            if (from != uint160(config.wallet)) revert ArgumentNotAllowed(selector, from);
            uint256 to = _word(data, 1);
            if (to != account) revert ArgumentNotAllowed(selector, to);
        } else if (selector == ACT) {
            // act(routeId, amount, minOutput, params) on StrategyManager. params[0:32] is where a
            // move sends the receipts: the account, zero or a sibling.
            if (target != strategyManager) revert TargetNotAllowed(selector, target);
            uint256 pointer = _word(data, 3);
            if (pointer != ACT_PARAMS_OFFSET) revert ArgumentNotAllowed(selector, pointer);
            // `params` holds its first word, so the word checked is the word Logic reads.
            uint256 length = _word(data, 4);
            if (length < 32) revert ArgumentNotAllowed(selector, length);
            uint256 recipient = _word(data, 5);
            if (
                recipient != account && recipient != 0 && recipient != uint160(config.sibling1)
                    && recipient != uint160(config.sibling2)
            ) revert ArgumentNotAllowed(selector, recipient);
        } else if (selector == COLLECT_FEE) {
            // collectFee(routeId, params) on StrategyManager.
            if (target != strategyManager) revert TargetNotAllowed(selector, target);
        } else if (selector == SET_PLAN) {
            // setPlan(plan) on Logic: the account's own plan.
            if (target != logic) revert TargetNotAllowed(selector, target);
            uint256 plan = _word(data, 0);
            if (plan != config.plan) revert ArgumentNotAllowed(selector, plan);
        } else if (selector == ENROLL) {
            // enroll(entryRouteId) on Logic: the plan, route, scope, one-position rule and price
            // are Logic's checks, for whoever calls.
            if (target != logic) revert TargetNotAllowed(selector, target);
        } else if (selector == UNINSTALL_VALIDATION) {
            // uninstallValidation(vId, …) on the account: only this session's validation id,
            // bytes21 0x02 ‖ permissionId ‖ zeros, left-aligned in its word as ABI encodes bytes21.
            if (target != msg.sender) revert TargetNotAllowed(selector, target);
            uint256 vId = _word(data, 0);
            if (bytes32(vId) != VALIDATION_TYPE_PERMISSION | (id >> 8)) revert ArgumentNotAllowed(selector, vId);
        } else {
            revert SelectorNotAllowed(selector);
        }
    }

    /// @dev The ABI head word `index` of a call's arguments. Reverts when the data is too short.
    function _word(bytes calldata data, uint256 index) private pure returns (uint256) {
        uint256 start = 4 + index * 32;
        return uint256(bytes32(data[start:start + 32]));
    }
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.