# WeightedECDSAValidator

> ERC7579のValidatorモジュールとして動作し、コントラクトアカウントに対して「ガーディアン」と呼ぶ複数の鍵保有者を登録してそれぞれに重み（weight）を付与して閾値を満たした場合にUserOperationを有効とする仕組みを

- URL: https://cardene.dev/books/kernel/bc91e9
- 本: Kernel (https://cardene.dev/books/kernel.md)
- 章: 12 / 13
- 前の章: https://cardene.dev/books/kernel/3d2e2e.md
- 次の章: https://cardene.dev/books/kernel/45d0b7.md
- 公開日: 2025-06-21
- 更新日: 2025-06-21
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

**ERC7579**のValidatorモジュールとして動作し、コントラクトアカウントに対して「ガーディアン」と呼ぶ複数の鍵保有者を登録してそれぞれに重み（weight）を付与して閾値を満たした場合にUserOperationを有効とする仕組みを提供します。
また、**EIP712**準拠の署名や提案（Proposal）への賛成／反対投票を管理し、一定の遅延（delay）を設けたうえで実行可能にするガバナンス機能を実装しています。

## コード

https://github.com/zerodevapp/kernel/blob/dev/src/validator/WeightedECDSAValidator.sol

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../types/Types.sol";
import {ECDSA} from "solady/utils/ECDSA.sol";
import {EIP712} from "solady/utils/EIP712.sol";
import {PackedUserOperation} from "../interfaces/PackedUserOperation.sol";
import {IValidator} from "../interfaces/IERC7579Modules.sol";
import {
    ERC1271_MAGICVALUE,
    ERC1271_INVALID,
    SIG_VALIDATION_FAILED_UINT,
    MODULE_TYPE_VALIDATOR,
    MODULE_TYPE_HOOK
} from "../types/Constants.sol";

struct WeightedECDSAValidatorStorage {
    uint24 totalWeight;
    uint24 threshold;
    uint48 delay;
    address firstGuardian;
}

struct GuardianStorage {
    uint24 weight;
    address nextGuardian;
}

enum ProposalStatus {
    Ongoing, // all proposal is ongoing by default
    Approved,
    Rejected,
    Executed
}

struct ProposalStorage {
    ProposalStatus status;
    ValidAfter validAfter;
}

enum VoteStatus {
    NA,
    Approved
}

struct VoteStorage {
    VoteStatus status;
}

contract WeightedECDSAValidator is EIP712, IValidator {
    mapping(address kernel => WeightedECDSAValidatorStorage) public weightedStorage;
    mapping(address guardian => mapping(address kernel => GuardianStorage)) public guardian;
    mapping(bytes32 callDataAndNonceHash => mapping(address kernel => ProposalStorage)) public proposalStatus;
    mapping(bytes32 callDataAndNonceHash => mapping(address guardian => mapping(address kernel => VoteStorage))) public
        voteStatus;

    event GuardianAdded(address indexed guardian, address indexed kernel, uint24 weight);
    event GuardianRemoved(address indexed guardian, address indexed kernel);

    function _domainNameAndVersion() internal pure override returns (string memory, string memory) {
        return ("WeightedECDSAValidator", "0.0.3");
    }

    function _addGuardians(address[] memory _guardians, uint24[] memory _weights, address _kernel) internal {
        uint24 totalWeight = weightedStorage[_kernel].totalWeight;
        require(_guardians.length == _weights.length, "Length mismatch");
        uint160 prevGuardian = uint160(weightedStorage[_kernel].firstGuardian);
        for (uint256 i = 0; i < _guardians.length; i++) {
            require(_guardians[i] != _kernel, "Guardian cannot be self");
            require(_guardians[i] != address(0), "Guardian cannot be 0");
            require(_weights[i] != 0, "Weight cannot be 0");
            require(guardian[_guardians[i]][_kernel].weight == 0, "Guardian already enabled");
            require(uint160(_guardians[i]) < prevGuardian, "Guardians not sorted");
            guardian[_guardians[i]][_kernel] =
                GuardianStorage({weight: _weights[i], nextGuardian: weightedStorage[_kernel].firstGuardian});
            weightedStorage[_kernel].firstGuardian = _guardians[i];
            totalWeight += _weights[i];
            prevGuardian = uint160(_guardians[i]);
            emit GuardianAdded(_guardians[i], _kernel, _weights[i]);
        }
        weightedStorage[_kernel].totalWeight = totalWeight;
    }

    function onInstall(bytes calldata _data) external payable override {
        (address[] memory _guardians, uint24[] memory _weights, uint24 _threshold, uint48 _delay) =
            abi.decode(_data, (address[], uint24[], uint24, uint48));
        require(_guardians.length == _weights.length, "Length mismatch");
        if (_isInitialized(msg.sender)) revert AlreadyInitialized(msg.sender);
        weightedStorage[msg.sender].firstGuardian = address(uint160(type(uint160).max));
        _addGuardians(_guardians, _weights, msg.sender);
        weightedStorage[msg.sender].delay = _delay;
        weightedStorage[msg.sender].threshold = _threshold;
        require(_threshold <= weightedStorage[msg.sender].totalWeight, "Threshold too high");
    }

    function onUninstall(bytes calldata) external payable override {
        if (!_isInitialized(msg.sender)) revert NotInitialized(msg.sender);
        address currentGuardian = weightedStorage[msg.sender].firstGuardian;
        while (currentGuardian != address(uint160(type(uint160).max))) {
            address nextGuardian = guardian[currentGuardian][msg.sender].nextGuardian;
            emit GuardianRemoved(currentGuardian, msg.sender);
            delete guardian[currentGuardian][msg.sender];
            currentGuardian = nextGuardian;
        }
        delete weightedStorage[msg.sender];
    }

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

    function isInitialized(address smartAccount) external view returns (bool) {
        return _isInitialized(smartAccount);
    }

    function _isInitialized(address smartAccount) internal view returns (bool) {
        return weightedStorage[smartAccount].totalWeight != 0;
    }

    function renew(address[] calldata _guardians, uint24[] calldata _weights, uint24 _threshold, uint48 _delay)
        external
        payable
    {
        if (!_isInitialized(msg.sender)) revert NotInitialized(msg.sender);
        address currentGuardian = weightedStorage[msg.sender].firstGuardian;
        while (currentGuardian != address(uint160(type(uint160).max))) {
            address nextGuardian = guardian[currentGuardian][msg.sender].nextGuardian;
            emit GuardianRemoved(currentGuardian, msg.sender);
            delete guardian[currentGuardian][msg.sender];
            currentGuardian = nextGuardian;
        }
        delete weightedStorage[msg.sender];
        require(_guardians.length == _weights.length, "Length mismatch");
        weightedStorage[msg.sender].firstGuardian = address(uint160(type(uint160).max));
        _addGuardians(_guardians, _weights, msg.sender);
        weightedStorage[msg.sender].delay = _delay;
        weightedStorage[msg.sender].threshold = _threshold;
    }

    function approve(bytes32 _callDataAndNonceHash, address _kernel) external {
        require(guardian[msg.sender][_kernel].weight != 0, "Guardian not enabled");
        require(weightedStorage[_kernel].threshold != 0, "Kernel not enabled");
        ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][_kernel];
        require(proposal.status == ProposalStatus.Ongoing, "Proposal not ongoing");
        VoteStorage storage vote = voteStatus[_callDataAndNonceHash][msg.sender][_kernel];
        require(vote.status == VoteStatus.NA, "Already voted");
        vote.status = VoteStatus.Approved;
        (, bool isApproved) = getApproval(_kernel, _callDataAndNonceHash);
        if (isApproved) {
            proposal.status = ProposalStatus.Approved;
            proposal.validAfter = ValidAfter.wrap(uint48(block.timestamp + weightedStorage[_kernel].delay));
        }
    }

    function approveWithSig(bytes32 _callDataAndNonceHash, address _kernel, bytes calldata sigs) external {
        uint256 sigCount = sigs.length / 65;
        require(weightedStorage[_kernel].threshold != 0, "Kernel not enabled");
        ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][_kernel];
        require(proposal.status == ProposalStatus.Ongoing, "Proposal not ongoing");
        for (uint256 i = 0; i < sigCount; i++) {
            address signer = ECDSA.recover(
                _hashTypedData(
                    keccak256(abi.encode(keccak256("Approve(bytes32 callDataAndNonceHash)"), _callDataAndNonceHash))
                ),
                sigs[i * 65:(i + 1) * 65]
            );
            VoteStorage storage vote = voteStatus[_callDataAndNonceHash][signer][_kernel];
            require(vote.status == VoteStatus.NA, "Already voted");
            vote.status = VoteStatus.Approved;
        }

        (, bool isApproved) = getApproval(_kernel, _callDataAndNonceHash);
        if (isApproved) {
            proposal.status = ProposalStatus.Approved;
            proposal.validAfter = ValidAfter.wrap(uint48(block.timestamp + weightedStorage[_kernel].delay));
        }
    }

    function veto(bytes32 _callDataAndNonceHash) external {
        ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][msg.sender];
        require(
            proposal.status == ProposalStatus.Ongoing || proposal.status == ProposalStatus.Approved,
            "Proposal not ongoing"
        );
        proposal.status = ProposalStatus.Rejected;
    }

    function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
        external
        payable
        override
        returns (uint256)
    {
        bytes32 callDataAndNonceHash = keccak256(abi.encode(userOp.sender, userOp.callData, userOp.nonce));
        ProposalStorage storage proposal = proposalStatus[callDataAndNonceHash][msg.sender];
        WeightedECDSAValidatorStorage storage strg = weightedStorage[msg.sender];
        if (strg.threshold == 0) {
            return SIG_VALIDATION_FAILED_UINT;
        }
        (uint256 totalWeight, bool passed) = getApproval(msg.sender, callDataAndNonceHash);
        uint256 threshold = strg.threshold;
        if (proposal.status == ProposalStatus.Ongoing && !passed) {
            if (strg.delay != 0) {
                // if delay > 0, only allow proposal to be approved before execution
                return SIG_VALIDATION_FAILED_UINT;
            }
            bytes calldata sig = userOp.signature;
            // parse sig with 65 bytes
            uint256 sigCount = sig.length / 65;
            require(sigCount > 0, "No sig");
            address signer;
            VoteStorage storage vote;
            for (uint256 i = 0; i < sigCount - 1 && !passed; i++) {
                signer = ECDSA.recover(
                    _hashTypedData(
                        keccak256(abi.encode(keccak256("Approve(bytes32 callDataAndNonceHash)"), callDataAndNonceHash))
                    ),
                    sig[i * 65:(i + 1) * 65]
                );
                vote = voteStatus[callDataAndNonceHash][signer][msg.sender];
                if (vote.status != VoteStatus.NA) {
                    continue;
                } // skip if already voted
                vote.status = VoteStatus.Approved;
                totalWeight += guardian[signer][msg.sender].weight;
                if (totalWeight >= threshold) {
                    passed = true;
                }
            }
            // userOpHash verification for the last sig
            signer = ECDSA.recover(ECDSA.toEthSignedMessageHash(userOpHash), sig[sig.length - 65:]);
            vote = voteStatus[callDataAndNonceHash][signer][msg.sender];
            if (vote.status == VoteStatus.NA) {
                vote.status = VoteStatus.Approved;
                totalWeight += guardian[signer][msg.sender].weight;
                if (totalWeight >= threshold) {
                    passed = true;
                }
            }
            proposal.status = ProposalStatus.Executed;
            if (passed && guardian[signer][msg.sender].weight != 0) {
                return packValidationData(ValidAfter.wrap(0), ValidUntil.wrap(0));
            }
            return SIG_VALIDATION_FAILED_UINT;
        } else if (proposal.status == ProposalStatus.Approved || passed) {
            if (userOp.paymasterAndData.length == 0 || address(bytes20(userOp.paymasterAndData[0:20])) == address(0)) {
                address signer = ECDSA.recover(ECDSA.toEthSignedMessageHash(userOpHash), userOp.signature);
                if (guardian[signer][msg.sender].weight != 0) {
                    proposal.status = ProposalStatus.Executed;
                    return packValidationData(proposal.validAfter, ValidUntil.wrap(0));
                }
            } else {
                proposal.status = ProposalStatus.Executed;
                return packValidationData(proposal.validAfter, ValidUntil.wrap(0));
            }
        }
        return SIG_VALIDATION_FAILED_UINT;
    }

    function getApproval(address kernel, bytes32 hash) public view returns (uint256 approvals, bool passed) {
        WeightedECDSAValidatorStorage storage strg = weightedStorage[kernel];
        for (
            address currentGuardian = strg.firstGuardian;
            currentGuardian != address(0);
            currentGuardian = guardian[currentGuardian][kernel].nextGuardian
        ) {
            if (voteStatus[hash][currentGuardian][kernel].status == VoteStatus.Approved) {
                approvals += guardian[currentGuardian][kernel].weight;
            }
        }
        ProposalStorage storage proposal = proposalStatus[hash][kernel];
        if (proposal.status == ProposalStatus.Rejected) {
            passed = false;
        } else {
            passed = approvals >= strg.threshold;
        }
    }

    function isValidSignatureWithSender(address, bytes32 hash, bytes calldata data) external view returns (bytes4) {
        WeightedECDSAValidatorStorage storage strg = weightedStorage[msg.sender];
        if (strg.threshold == 0) {
            return ERC1271_INVALID;
        }

        uint256 sigCount = data.length / 65;
        if (sigCount == 0) {
            return ERC1271_INVALID;
        }
        uint256 totalWeight = 0;
        address prevSigner = address(uint160(type(uint160).max));
        for (uint256 i = 0; i < sigCount; i++) {
            address signer = ECDSA.recover(hash, data[i * 65:(i + 1) * 65]);
            totalWeight += guardian[signer][msg.sender].weight;
            if (totalWeight >= strg.threshold) {
                return ERC1271_MAGICVALUE;
            }
            if (signer >= prevSigner) {
                return ERC1271_INVALID;
            }
            prevSigner = signer;
        }
        return ERC1271_INVALID;
    }
}
```

### `WeightedECDSAValidatorStorage`

```solidity
struct WeightedECDSAValidatorStorage {
    uint24 totalWeight;
    uint24 threshold;
    uint48 delay;
    address firstGuardian;
}
```

コントラクトアカウントごとのガーディアン設定を保持する構造体。
* `totalWeight`
    * 登録された全ガーディアンの重みの合計。
* `threshold`
    * UserOperation 実行に必要な重みの閾値。
* `delay`
    * 提案承認後から実行可能になるまでの遅延秒数。
* `firstGuardian`
    * 登録されたガーディアンを単方向リストでつなぐ際の先頭ガーディアンアドレス。

**パラメータ**

* `totalWeight`
    * 現在登録中の全ガーディアンの合計重み。
* `threshold`
    * 提案を承認と見なすために必要な合計重み。
* `delay`
    * 承認後に実行まで待機する秒数。
* `firstGuardian`
    * 最初に登録されたガーディアンのアドレス（リストのヘッド）。

### `GuardianStorage`

```solidity
struct GuardianStorage {
    uint24 weight;
    address nextGuardian;
}
```

個々のガーディアン設定を保持する構造体。
* `weight`
    * 当該ガーディアンの重み。
* `nextGuardian`
    * 次のガーディアンのアドレス（単方向リスト）。

**パラメータ**

* `weight`
    * ガーディアンに割り当てられた重み。
* `nextGuardian`
    * リスト次要素のガーディアンアドレス。

### `ProposalStorage`

```solidity
struct ProposalStorage {
    ProposalStatus status;
    ValidAfter validAfter;
}
```

各提案（callData＋nonce ハッシュ）ごとの状態を保持する構造体。
* `status`
    * 現在の提案状態（進行中／承認／拒否／実行済み）。
* `validAfter`
    * 承認後に実行可能となるタイムスタンプ。

**パラメータ**

* `status`
    * `ProposalStatus` 列挙型で示される状態。
* `validAfter`
    * 実行開始可能時刻を表す `ValidAfter` 型。

### `VoteStorage`

```solidity
struct VoteStorage {
    VoteStatus status;
}
```

ガーディアンごとの提案に対する投票状態を保持する構造体。
* `status`
    * 投票状況（未投票／承認済み）。

**パラメータ**

* `status`
    * `VoteStatus` 列挙型で示される投票状態。

### `ProposalStatus`

```solidity
enum ProposalStatus {
    Ongoing, // all proposal is ongoing by default
    Approved,
    Rejected,
    Executed
}
```

提案の進行状態を示す列挙型。
* `Ongoing`
    * 進行中（デフォルト）。
* `Approved`
    * 承認済み。
* `Rejected`
    * 拒否済み。
* `Executed`
    * 実行済み。

### `VoteStatus`

```solidity
enum VoteStatus {
    NA,
    Approved
}
```

ガーディアンの投票状態を示す列挙型。
* `NA`
    * 未投票。
* `Approved`
    * 承認投票済み。

### `weightedStorage`

```solidity
mapping(address kernel => WeightedECDSAValidatorStorage) public weightedStorage;
```

コントラクトアカウント（kernel）ごとの `WeightedECDSAValidatorStorage` を管理するマッピング配列。

* `kernel` をキーに、そのアカウントのガーディアン設定を参照・更新できます。

### `guardian`

```solidity
mapping(address guardian => mapping(address kernel => GuardianStorage)) public guardian;
```

各ガーディアンがどのコントラクトアカウントに対してどのように登録されているかを管理するマッピング配列。

### `proposalStatus`

```solidity
mapping(bytes32 callDataAndNonceHash => mapping(address kernel => ProposalStorage)) public proposalStatus;
```

提案（callData＋nonce のハッシュ）ごとに各コントラクトアカウントの提案状態を管理するマッピング配列。
`callDataAndNonceHash` をキーにして、コントラクトアカウント単位で `ProposalStorage` を参照できます。

### `voteStatus`

```solidity
mapping(
    bytes32 callDataAndNonceHash =>
      mapping(address guardian => mapping(address kernel => VoteStorage))
) public voteStatus;
```

提案ごとに各ガーディアンの投票状態を管理するマッピング配列。
`callDataAndNonceHash`、ガーディアン、コントラクトアカウントの３階層のマッピングで投票情報を保持します。

### `GuardianAdded`

```solidity
event GuardianAdded(address indexed guardian, address indexed kernel, uint24 weight);
```

ガーディアンを追加したときに発行されるイベント。
`_addGuardians` 実行時に、新規ガーディアンとその重みをイベントに残します。

**パラメータ**

* `guardian`
    * 追加されたガーディアンアドレス。
* `kernel`
    * ガーディアンを追加したコントラクトアカウント。
* `weight`
    * 割り当てられた重み。

### `GuardianRemoved`

```solidity
event GuardianRemoved(address indexed guardian, address indexed kernel);
```

ガーディアンを削除したときに発行されるイベント。
`onUninstall` や `renew`、`approve` の内部でガーディアン解除時に発行されます。

**パラメータ**

* `guardian`
    * 削除されたガーディアンアドレス。
* `kernel`
    * ガーディアンを削除したコントラクトアカウント。

### `_domainNameAndVersion`

```solidity
function _domainNameAndVersion() internal pure override returns (string memory, string memory) {
    return ("WeightedECDSAValidator", "0.0.3");
}
```

**EIP712**ドメイン名とバージョンを返す内部関数。
**EIP712**のドメインセパレータ生成に使用される名称とバージョンを指定します。

**戻り値**

* `string memory`
    * ドメイン名（ここでは `"WeightedECDSAValidator"`）。
* `string memory`
    * ドメインバージョン（ここでは `"0.0.3"`）。

### `_addGuardians`

```solidity
function _addGuardians(address[] memory _guardians, uint24[] memory _weights, address _kernel) internal {
    uint24 totalWeight = weightedStorage[_kernel].totalWeight;
    require(_guardians.length == _weights.length, "Length mismatch");
    uint160 prevGuardian = uint160(weightedStorage[_kernel].firstGuardian);
    for (uint256 i = 0; i < _guardians.length; i++) {
        require(_guardians[i] != _kernel, "Guardian cannot be self");
        require(_guardians[i] != address(0), "Guardian cannot be 0");
        require(_weights[i] != 0, "Weight cannot be 0");
        require(guardian[_guardians[i]][_kernel].weight == 0, "Guardian already enabled");
        require(uint160(_guardians[i]) < prevGuardian, "Guardians not sorted");
        guardian[_guardians[i]][_kernel] =
            GuardianStorage({weight: _weights[i], nextGuardian: weightedStorage[_kernel].firstGuardian});
        weightedStorage[_kernel].firstGuardian = _guardians[i];
        totalWeight += _weights[i];
        prevGuardian = uint160(_guardians[i]);
        emit GuardianAdded(_guardians[i], _kernel, _weights[i]);
    }
    weightedStorage[_kernel].totalWeight = totalWeight;
}
```

複数のガーディアンをコントラクトアカウントに追加する内部関数。

1. 引数の配列長が一致するかチェックします。
2. ソート順（アドレス昇順）と重みの妥当性を検証します。
3. 各ガーディアンを単方向リストに追加し、`totalWeight` を更新します。
4. 追加ごとに `GuardianAdded` イベントを発行します。

**引数**

* `_guardians`
    * 追加対象のガーディアンアドレス配列。
* `_weights`
    * 各ガーディアンに割り当てる重みの配列。
* `_kernel`
    * ガーディアンを追加するコントラクトアカウントのアドレス。

### `onInstall`

```solidity
function onInstall(bytes calldata _data) external payable override {
    (address[] memory _guardians, uint24[] memory _weights, uint24 _threshold, uint48 _delay) =
        abi.decode(_data, (address[], uint24[], uint24, uint48));
    require(_guardians.length == _weights.length, "Length mismatch");
    if (_isInitialized(msg.sender)) revert AlreadyInitialized(msg.sender);
    weightedStorage[msg.sender].firstGuardian = address(uint160(type(uint160).max));
    _addGuardians(_guardians, _weights, msg.sender);
    weightedStorage[msg.sender].delay = _delay;
    weightedStorage[msg.sender].threshold = _threshold;
    require(_threshold <= weightedStorage[msg.sender].totalWeight, "Threshold too high");
}
```

ガーディアンを含むマルチシグ設定をコントラクトアカウントにインストールする関数。

1. `_data` を `guardians`、`weights`、`threshold`、`delay` にデコードします。
2. すでに初期化済みなら `AlreadyInitialized` エラーを返します。
3. リスト初期化後に `_addGuardians` でガーディアンを登録し、`delay` と `threshold` を設定します。
4. `threshold` が `totalWeight` を超えないかを検証します。

**引数**

* `_data`
    * `(address[] guardians, uint24[] weights, uint24 threshold, uint48 delay)` としてエンコードされた初期化データ。

### `onUninstall`

```solidity
function onUninstall(bytes calldata) external payable override {
    if (!_isInitialized(msg.sender)) revert NotInitialized(msg.sender);
    address currentGuardian = weightedStorage[msg.sender].firstGuardian;
    while (currentGuardian != address(uint160(type(uint160).max))) {
        address nextGuardian = guardian[currentGuardian][msg.sender].nextGuardian;
        emit GuardianRemoved(currentGuardian, msg.sender);
        delete guardian[currentGuardian][msg.sender];
        currentGuardian = nextGuardian;
    }
    delete weightedStorage[msg.sender];
}
```

モジュールをアンインストールし、全てのガーディアン設定を削除する関数。

1. 初期化状態をチェックし、未初期化なら `NotInitialized` エラーを返します。
2. リストを巡回しながら `GuardianRemoved` イベントを発行し、各 `guardian` ストレージを削除します。
3. 最後に `weightedStorage` を削除して完全にリセットします。

**引数**

* （未使用）

### `isModuleType`

```solidity
function isModuleType(uint256 moduleTypeId) external pure override returns (bool) {
    return moduleTypeId == MODULE_TYPE_VALIDATOR;
}
```

このコントラクトが Validator モジュールかどうかを返す関数。

**詳細**

* `moduleTypeId` が **MODULE\_TYPE\_VALIDATOR** であれば `true`、そうでなければ `false` を返します。

**引数**

* `moduleTypeId`
    * 判定対象のモジュール種別 ID。

**戻り値**

* `bool`
    * Validatorモジュールなら `true`、それ以外は `false`。

### `isInitialized`

```solidity
function isInitialized(address smartAccount) external view override returns (bool) {
    return _isInitialized(smartAccount);
}
```

コントラクトアカウントが初期化済みかを返す関数。
内部関数 `_isInitialized` を呼び出して `totalWeight != 0` をチェックします。

**引数**

* `smartAccount`
    * 初期化状態をチェックしたいコントラクトアカウントのアドレス。

**戻り値**

* `bool`
    * 初期化済みなら `true`、未初期化なら `false`。

### `_isInitialized`

```solidity
function _isInitialized(address smartAccount) internal view returns (bool) {
    return weightedStorage[smartAccount].totalWeight != 0;
}
```

内部的にコントラクトアカウントの初期化状態を判定する関数。
`totalWeight` がゼロでないかを確認します。

**引数**

* `smartAccount`
    * 判定対象のコントラクトアカウントアドレス。

**戻り値**

* `bool`
    * 初期化済みなら `true`、未初期化なら `false`。

### `renew`

```solidity
function renew(address[] calldata _guardians, uint24[] calldata _weights, uint24 _threshold, uint48 _delay)
    external payable
{
    if (!_isInitialized(msg.sender)) revert NotInitialized(msg.sender);
    address currentGuardian = weightedStorage[msg.sender].firstGuardian;
    while (currentGuardian != address(uint160(type(uint160).max))) {
        address nextGuardian = guardian[currentGuardian][msg.sender].nextGuardian;
        emit GuardianRemoved(currentGuardian, msg.sender);
        delete guardian[currentGuardian][msg.sender];
        currentGuardian = nextGuardian;
    }
    delete weightedStorage[msg.sender];
    require(_guardians.length == _weights.length, "Length mismatch");
    weightedStorage[msg.sender].firstGuardian = address(uint160(type(uint160).max));
    _addGuardians(_guardians, _weights, msg.sender);
    weightedStorage[msg.sender].delay = _delay;
    weightedStorage[msg.sender].threshold = _threshold;
}
```

既存設定を削除して再インストールする関数。

1. 初期化状態をチェックし、未初期化なら `NotInitialized` エラーを返します。
2. 現在のガーディアンをすべて削除し `weightedStorage` をクリアします。
3. 引数の配列長を検証し、`_addGuardians` で再登録します。
4. `delay` と `threshold` を更新します。

**引数**

* `_guardians`
    * 新規に登録するガーディアンアドレス配列。
* `_weights`
    * 各ガーディアンの重み配列。
* `_threshold`
    * 新しい承認閾値。
* `_delay`
    * 新しい実行遅延秒数。

### `approve`

```solidity
function approve(bytes32 _callDataAndNonceHash, address _kernel) external {
    require(guardian[msg.sender][_kernel].weight != 0, "Guardian not enabled");
    require(weightedStorage[_kernel].threshold != 0, "Kernel not enabled");
    ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][_kernel];
    require(proposal.status == ProposalStatus.Ongoing, "Proposal not ongoing");
    VoteStorage storage vote = voteStatus[_callDataAndNonceHash][msg.sender][_kernel];
    require(vote.status == VoteStatus.NA, "Already voted");
    vote.status = VoteStatus.Approved;
    (, bool isApproved) = getApproval(_kernel, _callDataAndNonceHash);
    if (isApproved) {
        proposal.status = ProposalStatus.Approved;
        proposal.validAfter = ValidAfter.wrap(uint48(block.timestamp + weightedStorage[_kernel].delay));
    }
}
```

ガーディアンが提案に賛成投票する関数。

1. 呼び出し元が有効ガーディアンか、かつコントラクトアカウントが初期化済みかをチェックします。
2. 提案状態が `Ongoing` か、投票済みでないかを検証します。
3. 投票状態を `Approved` に更新し、`getApproval` で合計重みが閾値を超えれば提案を `Approved` にし、`validAfter` を設定します。

**引数**

* `_callDataAndNonceHash`
    * 提案を一意に識別する `callData` と `nonce` のハッシュ。
* `_kernel`
    * 投票対象のコントラクトアカウントアドレス。

### `approveWithSig`

```solidity
function approveWithSig(bytes32 _callDataAndNonceHash, address _kernel, bytes calldata sigs) external {
    uint256 sigCount = sigs.length / 65;
    require(weightedStorage[_kernel].threshold != 0, "Kernel not enabled");
    ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][_kernel];
    require(proposal.status == ProposalStatus.Ongoing, "Proposal not ongoing");
    for (uint256 i = 0; i < sigCount; i++) {
        address signer = ECDSA.recover(
            _hashTypedData(
                keccak256(abi.encode(keccak256("Approve(bytes32 callDataAndNonceHash)"), _callDataAndNonceHash))
            ),
            sigs[i * 65:(i + 1) * 65]
        );
        VoteStorage storage vote = voteStatus[_callDataAndNonceHash][signer][_kernel];
        require(vote.status == VoteStatus.NA, "Already voted");
        vote.status = VoteStatus.Approved;
    }
    (, bool isApproved) = getApproval(_kernel, _callDataAndNonceHash);
    if (isApproved) {
        proposal.status = ProposalStatus.Approved;
        proposal.validAfter = ValidAfter.wrap(uint48(block.timestamp + weightedStorage[_kernel].delay));
    }
}
```

オフチェーン署名を使って一括で賛成投票する関数。

1. コントラクトアカウントが初期化済みか、提案が進行中かをチェックします。
2. 受け取った署名列を `65` バイト単位で分割し、**EIP712**形式で復号して各ガーディアンの賛成投票を記録します。
3. `getApproval` で閾値を超えれば提案を `Approved` にし、`validAfter` を設定します。

**引数**

* `_callDataAndNonceHash`
    * 提案を識別するハッシュ。
* `_kernel`
    * 対象のコントラクトアカウント。
* `sigs`
    * ガーディアンの**EIP712**署名を連結したバイト列。

### `veto`

```solidity
function veto(bytes32 _callDataAndNonceHash) external {
    ProposalStorage storage proposal = proposalStatus[_callDataAndNonceHash][msg.sender];
    require(
        proposal.status == ProposalStatus.Ongoing || proposal.status == ProposalStatus.Approved,
        "Proposal not ongoing"
    );
    proposal.status = ProposalStatus.Rejected;
}
```

コントラクトアカウント自身が提案を拒否する関数。
* 提案状態が `Ongoing` または `Approved` の場合に限り、`Rejected` に変更します。

**引数**

* `_callDataAndNonceHash`
    * 対象提案のハッシュ。

### `validateUserOp`

```solidity
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
    external payable override returns (uint256)
{ ... }
```

UserOperationの承認可否をガーディアン投票をもとに判断する関数。

1. `callDataAndNonceHash` を計算し、該当提案の `ProposalStorage` を取得します。
2. `threshold` が 0 の場合は失敗コードを返します。
3. 提案が進行中かつ閾値未達の場合以下の処理を実行します。
    * `delay` が 0 ならオフチェーン署名をUserOperationの署名から取り出して賛成投票を更新し、
    * 最後のシグネチャで `proposal.status` を `Executed` にし、閾値を超えれば `packValidationData(ValidAfter.wrap(0), ValidUntil.wrap(0))` を返します。
    * 閾値に達しなければ `SIG_VALIDATION_FAILED_UINT` エラーを返します。
4. 提案が `Approved` または閾値超過している場合以下の処理を実行します。
    * Paymaster未使用またはゼロアドレスでない場合、UserOperationの最後の署名を検証し正常なら `packValidationData(validAfter, ValidUntil.wrap(0))` を返します。
5. いずれにも該当しないときは `SIG_VALIDATION_FAILED_UINT` エラーを返します。

**引数**

* `userOp`
    * 検証対象の **PackedUserOperation**。
* `userOpHash`
    * 検証用ハッシュ。

**戻り値**

* `uint256`
    * 承認結果コードまたは失敗コード。

### `getApproval`

```solidity
function getApproval(address kernel, bytes32 hash) public view returns (uint256 approvals, bool passed) { ... }
```

ガーディアン投票の合計重みと閾値超過判定を返す関数。

1. `weightedStorage[kernel].firstGuardian` からリストをたどり、賛成投票済みガーディアンの重みを合計します。
2. 提案が `Rejected` 状態なら `passed=false`、そうでなければ `approvals >= threshold` で判定します。

**引数**

* `kernel`
    * 対象のコントラクトアカウント。
* `hash`
    * `callDataAndNonceHash`。

**戻り値**

* `uint256 approvals`
    * 賛成投票済みガーディアンの合計重み。
* `bool passed`
    * 閾値を超えていれば `true`、そうでなければ `false`。

### `isValidSignatureWithSender`

```solidity
function isValidSignatureWithSender(address, bytes32 hash, bytes calldata data) external view returns (bytes4) { ... }
```

**ERC1271**形式でガーディアン集団のマルチシグ署名を検証する関数。

1. `threshold` が `0` なら `ERC1271_INVALID` を返します。
2. `data` を `65` バイト単位に分割し、各署名からガーディアンを復号して重みを累積します。
3. 累積重みが `threshold` を超えるかつ署名アドレスが降順になっていれば `ERC1271_MAGICVALUE`、そうでなければ `ERC1271_INVALID` エラーを返します。

**引数**

* （未使用）
* `hash`
    * 検証対象のハッシュ。
* `data`
    * 連結された複数のガーディアン署名バイト列。

**戻り値**

* `bytes4`
    * **ERC1271_MAGICVALUE** または **ERC1271_INVALID**。
