{"version":3,"sources":["../../operator/src/PaymasterOperatorClient.ts","../../operator/src/ProtocolClient.ts","../../operator/src/OperatorLifecycle.ts","../../operator/src/dvt/onboardDvtNode.ts","../../operator/src/dvt/resolveSigner.ts","../../operator/src/dvt/kmsPopSigner.ts"],"names":["BaseClient","registryActions","tokenActions","parseEther","paymasterFactoryActions","PaymasterABI","superPaymasterActions","paymasterActions","ProposalState","dvtActions","aggregatorActions","buildDvtPop","CANONICAL_ADDRESSES","dvtOperatorActions","ROLE_DVT","formatEther","AAStarBLSAlgorithmABI","isHex","privateKeyToAccount","encodeG1Point","dvtPopPoint","verifyDvtPop","keccak256"],"mappings":";;;;;;;AAmBO,IAAM,uBAAA,GAAN,cAAsCA,4BAAA,CAAW;AAAA,EAC7C,qBAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EAEP,YAAY,MAAA,EAA8B;AACtC,IAAA,KAAA,CAAM,MAAM,CAAA;AACZ,IAAA,IAAA,CAAK,wBAAwB,MAAA,CAAO,qBAAA;AACpC,IAAA,IAAA,CAAK,eAAe,MAAA,CAAO,YAAA;AAC3B,IAAA,IAAA,CAAK,eAAA,GAAkB,OAAO,sBAAA,IAA0B,4CAAA;AACxD,IAAA,IAAA,CAAK,YAAA,GAAe,OAAO,mBAAA,IAAuB,4CAAA;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAM,gCAAA,CAAiC,MAAA,EAGpC,OAAA,EAA6C;AAC5C,IAAA,IAAI;AACA,MAAA,MAAM,YAAA,GAAe,KAAK,eAAA,EAAgB;AAC1C,MAAA,MAAM,UAAA,GAAa,KAAK,aAAA,EAAc;AACtC,MAAA,MAAM,iBAAA,GAAoB,KAAK,oBAAA,EAAqB;AAEpD,MAAA,MAAM,QAAA,GAAWC,kCAAgB,YAAY,CAAA;AAC7C,MAAA,MAAM,S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;AAG3C,IAAA,IAAI,aAAa,SAAA,CAAU,WAAA,EAAY,KAAM,SAAA,CAAU,aAAY,EAAG;AAClE,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OAEJ;AAAA,IACJ;AAEA,IAAA,IAAIC,6BAAA,CAAY,SAAS,CAAA,CAAE,WAAA,OAAkB,CAAA,CAAE,QAAA,CAAS,aAAY,EAAG;AACnE,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OAEJ;AAAA,IACJ;AAEA,IAAAC,8BAAA,CAAa,EAAE,WAAW,QAAA,EAAU,CAAA,CAAE,UAAU,MAAA,EAAQ,CAAA,CAAE,QAAQ,CAAA;AAGlE,IAAA,OAAO,EAAE,SAAA,EAAW,QAAA,EAAU,CAAA,CAAE,QAAA,EAAU,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAQ,MAAA,EAAQC,cAAA,CAAU,SAAS,CAAA,EAAE;AAAA,EAC7F,CAAA;AACJ","file":"chunk-QZGPPUWJ.cjs","sourcesContent":["import { type Address, type Hash, parseEther } from 'viem';\nimport { BaseClient, type ClientConfig, type TransactionOptions, PaymasterABI } from '@aastar/core';\nimport { superPaymasterActions, tokenActions, paymasterActions, registryActions, paymasterFactoryActions } from '@aastar/core';\n\nexport interface OperatorClientConfig extends ClientConfig {\n    superPaymasterAddress: Address;\n    tokenAddress?: Address;\n}\n\nexport interface SponsorshipPolicy {\n    globalLimit: bigint;\n    userLimit: bigint;\n    itemPrice: bigint;\n    // ... logic for encoding this into bytes/storage\n}\n\n/**\n * Client for Paymaster Operators (ROLE_PAYMASTER_SUPER)\n */\nexport class PaymasterOperatorClient extends BaseClient {\n    public superPaymasterAddress: Address;\n    public tokenAddress?: Address;\n    public ethUsdPriceFeed: Address;\n    public xpntsFactory: Address;\n\n    constructor(config: OperatorClientConfig) {\n        super(config);\n        this.superPaymasterAddress = config.superPaymasterAddress;\n        this.tokenAddress = config.tokenAddress;\n        this.ethUsdPriceFeed = config.ethUsdPriceFeedAddress || '0x694AA1769357215DE4FAC081bf1f309aDC325306'; // Default Sepolia\n        this.xpntsFactory = config.xpntsFactoryAddress || '0x0000000000000000000000000000000000000000'; // Should be provided\n    }\n\n    // ========================================\n    // 0. 注册与入驻 (One-Stop Registration)\n    // ========================================\n\n    /**\n     * Register as SuperPaymaster Operator (one-stop API).\n     * This method handles all necessary steps:\n     * 1. Checks prerequisites (must have ROLE_COMMUNITY)\n     * 2. Checks and approves GToken to GTokenStaking\n     * 3. Registers ROLE_PAYMASTER_SUPER\n     * 4. Optionally deposits collateral to SuperPaymaster\n     * \n     * @param params Registration parameters\n     * @param options Transaction options\n     * @returns Transaction hash of role registration\n     */\n    async registerAsSuperPaymasterOperator(params?: {\n        stakeAmount?: bigint; // Optional, defaults to 50 GToken (Registry requirement)\n        depositAmount?: bigint; // Optional initial deposit to SuperPaymaster\n    }, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const registryAddr = this.requireRegistry();\n            const gTokenAddr = this.requireGToken();\n            const gTokenStakingAddr = this.requireGTokenStaking();\n            \n            const registry = registryActions(registryAddr);\n            const gToken = tokenActions();\n            const publicClient = this.getStartPublicClient();\n            \n            // 1. Check prerequisites\n            const ROLE_COMMUNITY = await registry(publicClient).ROLE_COMMUNITY();\n            const hasCommunity = await registry(publicClient).hasRole({\n                user: this.getAddress(),\n                roleId: ROLE_COMMUNITY\n            });\n            \n            if (!hasCommunity) {\n                throw new Error('Must have ROLE_COMMUNITY before registering as SuperPaymaster operator');\n            }\n            \n            // 2. Check if already has role\n            const ROLE_PAYMASTER_SUPER = await registry(publicClient).ROLE_PAYMASTER_SUPER();\n            const hasSuper = await registry(publicClient).hasRole({\n                user: this.getAddress(),\n                roleId: ROLE_PAYMASTER_SUPER\n            });\n            \n            if (hasSuper) {\n                // Still handle deposit if requested\n                if (params?.depositAmount) {\n                    return this.depositCollateral(params.depositAmount, options);\n                }\n                throw new Error('Already registered as SuperPaymaster operator');\n            }\n            \n            // 3. Prepare stake amount (default 50 GToken as per Registry config)\n            const stakeAmount = params?.stakeAmount || parseEther('50');\n            \n            // 4. Check and approve GToken to GTokenStaking\n            const allowance = await gToken(publicClient).allowance({\n                token: gTokenAddr,\n                owner: this.getAddress(),\n                spender: gTokenStakingAddr\n            });\n            \n            if (allowance < stakeAmount) {\n                const approveHash = await gToken(this.client).approve({\n                    token: gTokenAddr,\n                    spender: gTokenStakingAddr,\n                    amount: stakeAmount * 2n, // Approve 2x for future use\n                    account: options?.account\n                });\n                await (publicClient as any).waitForTransactionReceipt({ hash: approveHash });\n            }\n            \n            // 5. Register ROLE_PAYMASTER_SUPER\n            const registerHash = await registry(this.client).registerRoleSelf({\n                roleId: ROLE_PAYMASTER_SUPER,\n                data: '0x', // SuperPaymaster role doesn't need special data\n                account: options?.account\n            });\n            \n            // Wait for registration to complete\n            await (publicClient as any).waitForTransactionReceipt({ hash: registerHash });\n            \n            // 6. Optional: Deposit collateral to SuperPaymaster\n            if (params?.depositAmount) {\n                await this.depositCollateral(params.depositAmount, options);\n            }\n            \n            return registerHash;\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Deploy a new Paymaster V4 and Register as AOA Operator (one-stop API).\n     * This method handles:\n     * 1. Checks prerequisites (ROLE_COMMUNITY)\n     * 2. Predicts new Paymaster address\n     * 3. Deploys Paymaster V4 via Factory\n     * 4. Registers ROLE_PAYMASTER_AOA with staking\n     * \n     * @param params Deployment parameters\n     * @param options Transaction options\n     * @returns Object containing new paymaster address and transaction hashes\n     */\n    async deployAndRegisterPaymasterV4(params?: {\n        stakeAmount?: bigint; // Optional, defaults to 30 GToken (Registry requirement for AOA)\n        version?: string; // Optional, defaults to Factory default or V4.0.0\n        salt?: bigint; // Optional, for deterministic deployment\n        priceFeed?: Address;\n    }, options?: TransactionOptions): Promise<{ \n        paymasterAddress: Address; \n        deployHash: Hash; \n        registerHash: Hash;\n    }> {\n        try {\n            const registryAddr = this.requireRegistry();\n            const gTokenAddr = this.requireGToken();\n            const gTokenStakingAddr = this.requireGTokenStaking();\n            const factoryAddr = this.requirePaymasterFactory();\n            \n            const registry = registryActions(registryAddr);\n            const gToken = tokenActions();\n            const factory = paymasterFactoryActions(factoryAddr);\n            const publicClient = this.getStartPublicClient();\n            \n            const account = options?.account || this.client.account || this.getAddress();\n            const accountAddr = typeof account === 'string' ? account : account.address;\n\n            // 1. Check prerequisites (ROLE_COMMUNITY)\n            const ROLE_COMMUNITY = await registry(publicClient).ROLE_COMMUNITY();\n            const hasCommunity = await registry(publicClient).hasRole({\n                user: accountAddr,\n                roleId: ROLE_COMMUNITY\n            });\n            \n            if (!hasCommunity) {\n                throw new Error('Must have ROLE_COMMUNITY before deploying Paymaster V4');\n            }\n\n            // 2. Deployment (Idempotent Check)\n            const existingPaymaster = await factory(publicClient).getPaymaster({ owner: accountAddr });\n            let deployHash: Hash = '0x0000000000000000000000000000000000000000000000000000000000000000';\n            let paymasterAddress: Address;\n\n            if (existingPaymaster && existingPaymaster !== '0x0000000000000000000000000000000000000000') {\n                console.log(`    ℹ️  Paymaster already deployed at: ${existingPaymaster}`);\n                paymasterAddress = existingPaymaster;\n            } else {\n                console.log('    🛠️ Deploying Paymaster V4 with args:', {\n                    entryPoint: this.requireEntryPoint(),\n                    owner: accountAddr,\n                    priceFeed: this.ethUsdPriceFeed,\n                    factory: factoryAddr\n                });\n\n                const { encodeFunctionData } = await import('viem');\n                const initData = encodeFunctionData({\n                    abi: PaymasterABI,\n                    functionName: 'initialize',\n                    args: [\n                        this.requireEntryPoint(), // EntryPoint v0.7\n                        accountAddr,\n                        accountAddr, // Treasury defaults to owner\n                        this.ethUsdPriceFeed,\n                        200n, // serviceFeeRate (2%)\n                        parseEther('0.1'), // maxGasCostCap\n                        3600n // priceStalenessThreshold (1 hour)\n                    ]\n                });\n\n                deployHash = await factory(this.client).deployPaymaster({\n                    version: params?.version, \n                    initData,\n                    account\n                });\n                \n                await (publicClient as any).waitForTransactionReceipt({ hash: deployHash });\n                \n                paymasterAddress = await factory(publicClient).getPaymaster({ owner: accountAddr });\n            }\n            \n            if (!paymasterAddress || paymasterAddress === '0x0000000000000000000000000000000000000000') {\n                 throw new Error('Failed to retrieve Paymaster address from Factory');\n            }\n\n            // 3. Register ROLE_PAYMASTER_AOA\n            const ROLE_PAYMASTER_AOA = await registry(publicClient).ROLE_PAYMASTER_AOA();\n            const hasAOA = await registry(publicClient).hasRole({\n                user: accountAddr,\n                roleId: ROLE_PAYMASTER_AOA\n            });\n\n            if (hasAOA) {\n                return { paymasterAddress, deployHash, registerHash: '0x0000000000000000000000000000000000000000000000000000000000000000' };\n            }\n\n            const stakeAmount = params?.stakeAmount || parseEther('30');\n            \n            const allowance = await gToken(publicClient).allowance({\n                token: gTokenAddr,\n                owner: accountAddr,\n                spender: gTokenStakingAddr\n            });\n            \n            if (allowance < stakeAmount) {\n                const approveHash = await gToken(this.client).approve({\n                    token: gTokenAddr,\n                    spender: gTokenStakingAddr,\n                    amount: stakeAmount * 2n,\n                    account: account\n                });\n                await (publicClient as any).waitForTransactionReceipt({ hash: approveHash });\n            }\n\n            const { encodeAbiParameters, parseAbiParameters } = await import('viem');\n            let roleData: Hash = '0x';\n            if (stakeAmount > 0) {\n                roleData = encodeAbiParameters(\n                    parseAbiParameters('uint256'),\n                    [stakeAmount]\n                ) as Hash;\n            }\n\n            const registerHash = await registry(this.client).registerRoleSelf({\n                roleId: ROLE_PAYMASTER_AOA,\n                data: roleData,\n                account: account\n            });\n            \n            await (publicClient as any).waitForTransactionReceipt({ hash: registerHash });\n\n            return {\n                paymasterAddress,\n                deployHash,\n                registerHash\n            };\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Deposit collateral (aPNTs/GToken) to SuperPaymaster.\n     * This is a helper method used by registerAsSuperPaymasterOperator.\n     */\n    async depositCollateral(amount: bigint, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const pm = superPaymasterActions(this.superPaymasterAddress);\n            const publicClient = this.getStartPublicClient();\n            \n            // V3.7: Dynamically fetch the token expected by SuperPaymaster\n            const depositToken = await pm(publicClient).APNTS_TOKEN();\n            const token = tokenActions();\n            \n            // Approve SuperPaymaster to spend the token (usually aPNTs on Sepolia)\n            const allowance = await token(publicClient).allowance({\n                token: depositToken,\n                owner: this.getAddress(),\n                spender: this.superPaymasterAddress\n            });\n            \n            if (allowance < amount) {\n                const approveHash = await token(this.client).approve({\n                    token: depositToken,\n                    spender: this.superPaymasterAddress,\n                    amount,\n                    account: options?.account\n                });\n                await (publicClient as any).waitForTransactionReceipt({ hash: approveHash });\n            }\n            \n            // Deposit to SuperPaymaster\n            return pm(this.client).deposit({\n                amount,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Configure operator parameters (Token, Treasury).\n     * Exchange rate is now read live from xPNTsToken.exchangeRate() at runtime.\n     * If parameters are undefined, existing values are preserved.\n     */\n    async configureOperator(\n        xPNTsToken?: Address,\n        treasury?: Address,\n        options?: TransactionOptions\n    ): Promise<Hash> {\n        try {\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            const publicClient = this.getStartPublicClient();\n\n            // Fetch current config to preserve missing values\n            const currentConfig = await sp(publicClient).operators({ operator: this.getAddress() });\n\n            const currentToken = currentConfig.xPNTsToken;\n            const currentTreasury = currentConfig.treasury;\n\n            return await sp(this.client).configureOperator({\n                xPNTsToken: xPNTsToken || currentToken,\n                opTreasury: treasury || currentTreasury,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async withdrawCollateral(to: Address, amount: bigint, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            return await sp(this.client).withdrawTo({\n                to,\n                amount,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async isOperator(operator: Address): Promise<boolean> {\n        try {\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            const config = await sp(this.getStartPublicClient()).operators({ operator });\n            return config.isConfigured;\n        } catch (error) {\n            return false;\n        }\n    }\n\n    async getOperatorDetails(operator?: Address): Promise<any> {\n        try {\n            const target = operator || this.getAddress();\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            return await sp(this.getStartPublicClient()).operators({ operator: target });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async initiateExit(options?: TransactionOptions): Promise<Hash> {\n        try {\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            return await sp(this.client).unlockStake({\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async withdrawStake(to: Address, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            return await sp(this.client).withdrawStake({\n                to,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    // ========================================\n    // 3. 支付代币管理 (基于 PaymasterActions)\n    // ========================================\n\n    async addGasToken(token: Address, price: bigint, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const pm = paymasterActions(this.superPaymasterAddress);\n            return await pm(this.client).setTokenPrice({\n                token,\n                price,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async getTokenPrice(token: Address): Promise<bigint> {\n        try {\n            const pm = paymasterActions(this.superPaymasterAddress);\n            return await pm(this.getStartPublicClient()).tokenPrices({ token });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async setupPaymasterDeposit(params: {\n        paymaster: Address;\n        user: Address;\n        token: Address;\n        amount: bigint;\n    }, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const pm = paymasterActions(params.paymaster);\n            return await pm(this.client).depositFor({\n                user: params.user,\n                token: params.token,\n                amount: params.amount,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n}\n","import { type Address, type Hash, type Hex } from 'viem';\nimport { BaseClient, type ClientConfig, type TransactionOptions } from '@aastar/core';\nimport { dvtActions, aggregatorActions, superPaymasterActions } from '@aastar/core';\n\nexport interface ProtocolClientConfig extends ClientConfig {\n    dvtValidatorAddress: Address; // The DVT Validator contract (Governance)\n    blsAggregatorAddress?: Address; // Optional BLS Aggregator\n    superPaymasterAddress?: Address; // For Global Params\n}\n\nexport enum ProposalState {\n    Pending = 0,\n    Active = 1,\n    Canceled = 2,\n    Defeated = 3,\n    Succeeded = 4,\n    Queued = 5,\n    Expired = 6,\n    Executed = 7\n}\n\n/**\n * Client for Protocol Governors and Validators (Infrastructure)\n */\nexport class ProtocolClient extends BaseClient {\n    public dvtValidatorAddress: Address;\n    public blsAggregatorAddress?: Address;\n    public superPaymasterAddress?: Address;\n\n    constructor(config: ProtocolClientConfig) {\n        super(config);\n        this.dvtValidatorAddress = config.dvtValidatorAddress;\n        this.blsAggregatorAddress = config.blsAggregatorAddress;\n        this.superPaymasterAddress = config.superPaymasterAddress;\n    }\n\n    // ========================================\n    // 1. 提案管理 (DVT)\n    // ========================================\n\n    /**\n     * Create a new proposal\n     */\n    async createProposal(target: Address, calldata: Hex, description: string, options?: TransactionOptions): Promise<Hash> {\n        try {\n            const dvt = dvtActions(this.dvtValidatorAddress)(this.client);\n            \n            // Mapping general \"createProposal\" to \"createSlashProposal\" for now\n            // Assuming Governance uses Validator logic or this Client is for Slash.\n            // Using createSlashProposal as the available action.\n            return await dvt.createSlashProposal({\n                operator: target,\n                level: 1, // Default level\n                reason: description,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async signProposal(proposalId: bigint, signature: Hex = '0x', options?: TransactionOptions): Promise<Hash> {\n        try {\n            const dvt = dvtActions(this.dvtValidatorAddress)(this.client);\n            return await dvt.signSlashProposal({\n                proposalId,\n                signature,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Execute a proposal with collected signatures\n     */\n    async executeWithProof(_proposalId: bigint, _signatures: Hex[], _options?: TransactionOptions): Promise<Hash> {\n        // #169 lesson: never silently submit fake values. This previously sent proof='0x', repUsers=[],\n        // newScores=[], epoch=0n to a slashing call — garbage that ignored `signatures`. The real\n        // BLS-proof aggregation (signatures -> proof + repUsers/newScores/epoch) is not wired, so throw\n        // instead of submitting a broken slash.\n        throw new Error(\n            'ProtocolClient.executeWithProof is not implemented: BLS proof aggregation from signatures ' +\n            'is missing. Build the real proof + repUsers/newScores/epoch and call ' +\n            'dvtActions().executeSlashWithProof directly.',\n        );\n    }\n\n    // ========================================\n    // 2. 验证器管理 / BLS\n    // ========================================\n\n    async registerBLSKey(publicKey: Hex, options?: TransactionOptions): Promise<Hash> {\n        try {\n            if (!this.blsAggregatorAddress) {\n                throw new Error('BLS Aggregator address required for this client');\n            }\n            // Aggregator actions now handle the type internally or via mapping\n            const agg = aggregatorActions(this.blsAggregatorAddress)(this.client);\n            \n            return await agg.registerBLSPublicKey({\n                validator: this.getAddress(),\n                publicKey,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    // ========================================\n    // 3. 全局参数管理 (Admin)\n    // ========================================\n\n    async setProtocolFee(bps: bigint, options?: TransactionOptions): Promise<Hash> {\n        try {\n            if (!this.superPaymasterAddress) {\n                throw new Error('SuperPaymaster address required for this client');\n            }\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            \n            return await sp(this.client).setProtocolFee({\n                newFeeBPS: bps,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    async setTreasury(treasury: Address, options?: TransactionOptions): Promise<Hash> {\n        try {\n            if (!this.superPaymasterAddress) {\n                 throw new Error('SuperPaymaster address required for this client');\n            }\n            const sp = superPaymasterActions(this.superPaymasterAddress);\n            \n            return await sp(this.client).setTreasury({\n                treasury,\n                account: options?.account\n            });\n        } catch (error) {\n            throw error;\n        }\n    }\n}\n","import { type Address, type Hash, type Hex, parseEther } from 'viem';\nimport { type TransactionOptions } from '@aastar/core';\nimport { PaymasterOperatorClient, type OperatorClientConfig } from './PaymasterOperatorClient.js';\nimport { tokenActions, registryActions } from '@aastar/core'; // L2/L1 Actions\n\nexport interface OperatorStatus {\n    isConfigured: boolean;\n    isActive: boolean;\n    balance: bigint;\n}\n\n/**\n * OperatorLifecycle - L3 Pattern\n * \n * Responsibilities:\n * 1. Managing the complete lifecycle of a Paymaster Operator\n * 2. Unifying setup (onboard), operation (config), and exit (withdraw)\n */\nexport class OperatorLifecycle extends PaymasterOperatorClient {\n\n    constructor(config: OperatorClientConfig) {\n        super(config);\n    }\n\n    // ===========================================\n    // 1. Setup Phase (Onboarding)\n    // ===========================================\n\n    /**\n     * Check if the account is ready to become an operator\n     * (e.g., has GToken, has ROLE_COMMUNITY, etc.)\n     */\n    async checkReadiness(): Promise<OperatorStatus> {\n        const isOp = await this.isOperator(this.getAddress());\n        // For SuperPaymaster, balance is 'aPNTsBalance' (Collateral)\n        const details = await this.getOperatorDetails();\n        const balance = details.aPNTsBalance || 0n;\n        \n        return {\n            isConfigured: isOp,\n            isActive: isOp, // Simplification\n            balance\n        };\n    }\n\n    /**\n     * One-click Setup: Register + Deposit + Deploy Node\n     * Wraps existing registerAsSuperPaymasterOperator or deployAndRegisterPaymasterV4\n     */\n    async setupNode(params: {\n        type: 'V4' | 'SUPER';\n        stakeAmount?: bigint;\n        depositAmount?: bigint;\n    }, options?: TransactionOptions): Promise<Hash[]> {\n        const hashes: Hash[] = [];\n\n        if (params.type === 'SUPER') {\n            const h = await this.registerAsSuperPaymasterOperator({\n                stakeAmount: params.stakeAmount,\n                depositAmount: params.depositAmount\n            }, options);\n            hashes.push(h);\n\n            // Fetch Token Address and Configure\n            const factory = await import('@aastar/core').then(m => m.xPNTsFactoryActions(this.xpntsFactory!)(this.getStartPublicClient()));\n            const token = await factory.getTokenAddress({ community: this.getAddress() });\n            \n            if (token && token !== '0x0000000000000000000000000000000000000000') {\n                const hConfig = await this.configureOperator(\n                    token,\n                    this.getAddress(), // Default treasury to self\n                    options\n                );\n                hashes.push(hConfig);\n            }\n        } else {\n            const result = await this.deployAndRegisterPaymasterV4({\n                stakeAmount: params.stakeAmount\n            }, options);\n            hashes.push(result.deployHash);\n            hashes.push(result.registerHash);\n        }\n\n        return hashes;\n    }\n\n    // ===========================================\n    // 2. Operational Phase (Config & Funds)\n    // ===========================================\n\n    // Inherits: addGasToken, configureOperator, depositCollateral from PaymasterOperatorClient\n\n    async getOperatorStats(): Promise<any> {\n        return await this.getOperatorDetails();\n    }\n\n    // ===========================================\n    // 3. Exit Phase (Withdraw & Leave)\n    // ===========================================\n\n    /**\n     * Start the exit process: Unstake from Registry/SuperPaymaster and Unlock funds\n     */\n    async initiateExit(options?: TransactionOptions): Promise<Hash> {\n        // 1. Unlock Stake from SuperPaymaster (if applicable)\n        return await super.initiateExit(options);\n    }\n\n    /**\n     * Finalize exit: Withdraw all funds (Collateral + Rewards)\n     */\n    async withdrawAllFunds(to?: Address, options?: TransactionOptions): Promise<Hash[]> {\n        const recipient = to || this.getAddress();\n        const hashes: Hash[] = [];\n\n        // 1. Withdraw Collateral from SuperPaymaster (if any)\n        // Note: We need to know the balance to withdraw exact amount.\n        // For current L3 pattern, we assume the user tracks it or we fetch it.\n        const stats = await this.checkReadiness();\n        if (stats.balance > 0n) {\n             const hCol = await this.withdrawCollateral(recipient, stats.balance, options);\n             hashes.push(hCol);\n        }\n\n        // 2. Exit Role in Registry (Unstake GToken)\n        // This will fail if lock duration > 0 and not yet cooldown.\n        // Or it will initiate cooldown.\n        const client = this.getStartPublicClient();\n        const registry = registryActions(this.registryAddress as Address); // Use local registry address\n        const registryWriter = registryActions(this.registryAddress as Address)(this.client);\n        \n        // Check if we have the role\n        // For Super Operator\n        const ROLE_PAYMASTER_SUPER = await registry(client).ROLE_PAYMASTER_SUPER();\n        const hasRole = await registry(client).hasRole({ user: this.getAddress(), roleId: ROLE_PAYMASTER_SUPER });\n        \n        if (hasRole) {\n            const hExit = await registryWriter.exitRole({ roleId: ROLE_PAYMASTER_SUPER, account: options?.account });\n            hashes.push(hExit);\n        }\n\n        return hashes;\n    }\n\n    // Helper: Get GToken Balance\n    private async getTokenBalance(): Promise<bigint> {\n        if (!this.tokenAddress) return 0n;\n        const token = tokenActions()(this.getStartPublicClient());\n        return await token.balanceOf({ token: this.tokenAddress, account: this.getAddress() });\n    }\n}\n","import {\n    type Account,\n    type Address,\n    type Hash,\n    type Hex,\n    type PublicClient,\n    type WalletClient,\n    formatEther,\n    parseEther,\n} from 'viem';\nimport {\n    CANONICAL_ADDRESSES,\n    ROLE_DVT,\n    buildDvtPop,\n    dvtOperatorActions,\n    registryActions,\n    tokenActions,\n    type DvtPop,\n    AAStarBLSAlgorithmABI,\n} from '@aastar/core';\n\n/**\n * L2 workflow — one-click \"stake + register\" onboarding for a DVT node (CC-36).\n *\n * The staked DVT registration path (`AAStarBLSAlgorithm.registerWithProof`, YetAnotherAA-Validator #165)\n * requires the operator EOA to first hold **ROLE_DVT** stake (>= `minStake` GToken, locked in the linked\n * GTokenStaking registry) before it may bind a node. On-chain that is a 4-step dance the DVT\n * `register-node.mjs` script cannot fully perform on its own — it lacks the privilege to stake an unstaked\n * operator. This workflow composes the existing L1 actions (`tokenActions` / `registryActions` /\n * `dvtOperatorActions`) into a single idempotent call that the SDK, holding both keys, CAN complete:\n *\n *   0. Resolve the PoP tuple (local BLS key → {@link buildDvtPop}, a pre-built tuple, or a `popSigner`\n *      callback — the seam for a future KMS-TEE `/pop` endpoint) and derive `nodeId = keccak256(publicKey)`.\n *   1. Idempotency: if the operator already owns this node and it is registered, short-circuit success.\n *   2. Read `minStake` + ROLE_DVT `ticketPrice` → the GToken the operator must hold to register.\n *   3. (optional) `funderWallet` tops up the operator's ETH (gas) and GToken (stake) when either is low —\n *      this is the \"owner 代付\" model. Without a funder, an under-funded operator throws a clear error.\n *   4. Operator approves GToken → GTokenStaking, then `registerRole(ROLE_DVT)` (locks the stake). Verify\n *      `getEffectiveStake >= minStake`.\n *   5. Preflight `simulateContract(registerWithProof)` to catch any revert before spending gas.\n *   6. `registerWithProof(publicKey, popPoint, popSig)`; assert `isRegistered && nodeOperator == operator`.\n *\n * This mirrors, step-for-step, the on-chain-proven `tests/regression/onchain-evidence/dvt-register-e2e.ts`.\n *\n * SCOPE (CC-36 v1): covers nodes whose BLS secret key is held locally / in an HSM (the `blsSecretKey` or\n * pre-built `pop` inputs). A KMS-TEE **key-less** node cannot build its PoP here — the secret never leaves\n * the TEE — so it needs a KMS `/pop` endpoint that does not yet exist (cross-repo gap). The `popSigner`\n * callback is the forward seam for that: once KMS ships `/pop`, wire it as `popSigner` with no other change.\n */\nexport interface OnboardDvtNodeParams {\n    /** Read client. Its chain id selects the canonical address book when addresses are omitted. */\n    publicClient: PublicClient;\n    /**\n     * The operator EOA that stakes and registers (the on-chain `msg.sender` for `registerRole` and\n     * `registerWithProof`). Must be a WalletClient with an account bound.\n     */\n    operatorWallet: WalletClient;\n    /**\n     * Optional owner/funder wallet (\"owner 代付\"). When provided, tops up the operator's ETH and GToken\n     * if either falls short of what registration needs. When omitted, an under-funded operator aborts\n     * with a descriptive error instead of a mid-flow on-chain revert.\n     */\n    funderWallet?: WalletClient;\n\n    // ---- PoP input: provide exactly one ----\n    /** Local/HSM BLS secret key (32-byte hex). The PoP is built via {@link buildDvtPop}. */\n    blsSecretKey?: Hex;\n    /** A pre-built PoP tuple (e.g. produced by an external signer). */\n    pop?: DvtPop;\n    /** Async PoP provider — the seam for a future KMS-TEE `/pop` endpoint. */\n    popSigner?: () => Promise<DvtPop>;\n\n    // ---- addresses (default to CANONICAL_ADDRESSES[chainId]) ----\n    /** DVT validator (`AAStarBLSAlgorithm`). Default: canonical `aaStarBLSAlgorithm`. */\n    validator?: Address;\n    /** SuperPaymaster role Registry. Default: canonical `registry`. */\n    registry?: Address;\n    /** GToken (stake asset). Default: canonical `gToken`. */\n    gToken?: Address;\n    /** GTokenStaking (approval spender). Default: canonical `staking`. */\n    staking?: Address;\n\n    // ---- funding knobs ----\n    /** Fund the operator's ETH when its balance is below this. Default: 0.015 ETH. */\n    minOperatorEth?: bigint;\n    /** ETH amount the funder sends when topping up gas. Default: 0.03 ETH. */\n    topUpEth?: bigint;\n    /** Extra GToken headroom above `minStake + ticketPrice` when topping up stake. Default: 2 GToken. */\n    gTokenHeadroom?: bigint;\n\n    /**\n     * Perform NO on-chain writes: run the reads, compute the funding/stake plan, simulate\n     * `registerWithProof` when the operator is already staked, and return the {@link OnboardDvtNodeResult.plan}.\n     * No ETH/GToken is sent, no stake is locked, no node is bound.\n     */\n    dryRun?: boolean;\n}\n\n/** What a {@link onboardDvtNode} call WOULD do — populated only on a `dryRun`. All amounts in wei. */\nexport interface OnboardDvtNodePlan {\n    /** Whether the validator's staked-registration path is enabled. */\n    requireStake: boolean;\n    /** GToken the operator must hold before `registerRole` (`max(validator, registry minStake) + ticket + headroom`). */\n    needGToken: bigint;\n    /** ETH the funder would send to the operator (0 if already funded / no funder needed). */\n    wouldFundEth: bigint;\n    /** GToken the funder would transfer to the operator (0 if already funded). */\n    wouldFundGToken: bigint;\n    /** Whether a GToken→GTokenStaking approval would be submitted. */\n    wouldApprove: boolean;\n    /** Whether `registerRole(ROLE_DVT)` would be submitted (false when the operator already holds it). */\n    wouldRegisterRole: boolean;\n    /** Whether `registerWithProof` was simulated OK (only attempted when already staked; false otherwise). */\n    registerSimulated: boolean;\n}\n\nexport interface OnboardDvtNodeResult {\n    /** `keccak256(publicKey)` — the node bound (or that would be bound in a dry run). */\n    nodeId: Hex;\n    /** The node's 128-byte EIP-2537 G1 public key. */\n    publicKey: Hex;\n    /** The operator EOA. */\n    operator: Address;\n    /** True when the operator already owned this registered node — the flow short-circuited. */\n    alreadyRegistered: boolean;\n    /** True when this call newly registered the node (false on idempotent short-circuit or dry run). */\n    registered: boolean;\n    /** True when this call newly staked ROLE_DVT (false when the operator already held it). */\n    staked: boolean;\n    /** `getEffectiveStake(operator, ROLE_DVT)` after staking. */\n    effectiveStake: bigint;\n    /** `minStake()` the contract enforces. */\n    minStake: bigint;\n    /** Tx hashes for each step actually performed. */\n    hashes: {\n        fundEth?: Hash;\n        fundGToken?: Hash;\n        approve?: Hash;\n        registerRole?: Hash;\n        register?: Hash;\n    };\n    /** The dry-run plan — present ONLY when `dryRun` was set. */\n    plan?: OnboardDvtNodePlan;\n}\n\nconst ZERO_BYTES32 = '0x0000000000000000000000000000000000000000000000000000000000000000';\n\n/** Resolve the PoP tuple from whichever of the three mutually-exclusive inputs was supplied. */\nasync function resolvePop(params: OnboardDvtNodeParams): Promise<DvtPop> {\n    const supplied = [params.blsSecretKey, params.pop, params.popSigner].filter((v) => v !== undefined);\n    if (supplied.length !== 1) {\n        throw new Error(\n            'onboardDvtNode: provide exactly one PoP input — blsSecretKey, pop, or popSigner',\n        );\n    }\n    if (params.popSigner) return params.popSigner();\n    if (params.pop) return params.pop;\n    return buildDvtPop(params.blsSecretKey as Hex);\n}\n\n/**\n * Onboard a DVT node in one idempotent call: stake ROLE_DVT (funding the operator if a funder is given)\n * then bind the node via `registerWithProof`. See {@link OnboardDvtNodeParams} for the key model and scope.\n */\nexport async function onboardDvtNode(params: OnboardDvtNodeParams): Promise<OnboardDvtNodeResult> {\n    const { publicClient, operatorWallet, funderWallet, dryRun } = params;\n\n    const operator = operatorWallet.account?.address;\n    if (!operator) throw new Error('onboardDvtNode: operatorWallet must have an account bound');\n\n    // Resolve chain + canonical address book.\n    const chainId = operatorWallet.chain?.id ?? publicClient.chain?.id ?? (await publicClient.getChainId());\n    const canonical = CANONICAL_ADDRESSES[chainId as keyof typeof CANONICAL_ADDRESSES];\n    if (!canonical) throw new Error(`onboardDvtNode: no canonical address book for chain ${chainId}`);\n\n    const validator = params.validator ?? (canonical.aaStarBLSAlgorithm as Address);\n    const registry = params.registry ?? (canonical.registry as Address);\n    const gToken = params.gToken ?? (canonical.gToken as Address);\n    const staking = params.staking ?? (canonical.staking as Address);\n    if (!validator || BigInt(validator) === 0n) {\n        throw new Error(`onboardDvtNode: DVT validator address is unset/zero on chain ${chainId}`);\n    }\n\n    const minOperatorEth = params.minOperatorEth ?? parseEther('0.015');\n    const topUpEth = params.topUpEth ?? parseEther('0.03');\n    const gTokenHeadroom = params.gTokenHeadroom ?? parseEther('2');\n\n    // L1 action bindings.\n    const dvtRead = dvtOperatorActions(validator)(publicClient);\n    const dvtOp = dvtOperatorActions(validator)(operatorWallet);\n    const regRead = registryActions(registry)(publicClient);\n    const regOp = registryActions(registry)(operatorWallet);\n    const gtRead = tokenActions()(publicClient);\n    const gtOp = tokenActions()(operatorWallet);\n\n    // Wait for a receipt AND assert the tx did not revert — waitForTransactionReceipt resolves even for\n    // mined-but-reverted writes, so a bare await would silently treat a revert as success.\n    const waitSuccess = async (step: string, hash: Hash): Promise<Hash> => {\n        const receipt = await publicClient.waitForTransactionReceipt({ hash });\n        if (receipt.status !== 'success') {\n            throw new Error(`onboardDvtNode: ${step} tx ${hash} reverted on-chain (status=${receipt.status}).`);\n        }\n        return hash;\n    };\n    const maxBig = (a: bigint, b: bigint) => (a > b ? a : b);\n    const hashes: OnboardDvtNodeResult['hashes'] = {};\n\n    // --- 0. resolve PoP + nodeId ---\n    const pop = await resolvePop(params);\n    const { nodeId, publicKey } = pop;\n\n    // --- 1. idempotency (reads only) ---\n    const existingNode = await dvtRead.operatorNode({ operator });\n    if (existingNode && existingNode !== ZERO_BYTES32) {\n        if (existingNode.toLowerCase() === nodeId.toLowerCase()) {\n            // Operator already owns THIS node. If it is registered → idempotent success. If it owns the\n            // slot but is not registered (a partial/interrupted prior run), fall through and resume the\n            // registration — this is the same operator + same nodeId, so it is not a conflict.\n            if (await dvtRead.isRegistered({ nodeId })) {\n                const eff = await regRead.getEffectiveStake({ user: operator, roleId: ROLE_DVT });\n                const min = await dvtRead.minStake();\n                return {\n                    nodeId, publicKey, operator,\n                    alreadyRegistered: true, registered: false, staked: false,\n                    effectiveStake: eff, minStake: min, hashes,\n                };\n            }\n        } else {\n            // The contract binds one node per operator; a different existing node is a hard conflict.\n            throw new Error(\n                `onboardDvtNode: operator ${operator} already owns node ${existingNode}, ` +\n                `cannot bind a second node ${nodeId}. Use a different operator EOA.`,\n            );\n        }\n    }\n    // Guard against a nodeId already owned by someone else.\n    const nodeOwner = await dvtRead.nodeOperator({ nodeId });\n    if (nodeOwner && BigInt(nodeOwner) !== 0n && nodeOwner.toLowerCase() !== operator.toLowerCase()) {\n        throw new Error(`onboardDvtNode: nodeId ${nodeId} is already registered to ${nodeOwner}`);\n    }\n\n    // --- 2. stake requirements (reads only) ---\n    const minStake = await dvtRead.minStake(); // validator floor enforced at registerWithProof\n    const requireStake = await dvtRead.requireStake();\n    let needGToken = 0n;\n    if (requireStake) {\n        const cfg = await regRead.getRoleConfig({ roleId: ROLE_DVT });\n        const ticket = BigInt(cfg.ticketPrice ?? 0n);\n        // registerRole locks the REGISTRY's ROLE_DVT minStake; registerWithProof requires the VALIDATOR's\n        // minStake. If the registry floor is below the validator floor, staking can never satisfy the\n        // validator — fail fast BEFORE locking any GToken rather than lock-then-abort.\n        const registryMinStake = BigInt(cfg.minStake ?? 0n);\n        if (registryMinStake < minStake) {\n            throw new Error(\n                `onboardDvtNode: registry ROLE_DVT minStake ${formatEther(registryMinStake)} < validator ` +\n                `minStake ${formatEther(minStake)} — registerRole cannot lock enough to pass the validator ` +\n                `(contract misconfig). Aborting before staking.`,\n            );\n        }\n        // Hold enough GToken to cover the larger of the two floors, plus the ticket fee and headroom.\n        needGToken = maxBig(minStake, registryMinStake) + ticket + gTokenHeadroom;\n    }\n\n    // --- 3. compute the funding / staking plan (reads only) ---\n    // ETH gas is needed by ANY path that submits an operator tx (register, and the stake txs), so it is\n    // planned independently of requireStake. Top up to the threshold: max(topUpEth, deficit) guarantees a\n    // low custom topUpEth still reaches minOperatorEth.\n    const opEth = await publicClient.getBalance({ address: operator });\n    const wouldFundEth = opEth < minOperatorEth ? maxBig(topUpEth, minOperatorEth - opEth) : 0n;\n\n    let opGt = 0n;\n    let wouldApprove = false;\n    let hasRole = false;\n    let wouldFundGToken = 0n;\n    if (requireStake) {\n        opGt = (await gtRead.balanceOf({ token: gToken, account: operator })) as bigint;\n        wouldFundGToken = opGt < needGToken ? needGToken - opGt : 0n;\n        const allowance = (await gtRead.allowance({ token: gToken, owner: operator, spender: staking })) as bigint;\n        wouldApprove = allowance < needGToken;\n        hasRole = await regRead.hasRole({ roleId: ROLE_DVT, user: operator });\n    }\n    const wouldRegisterRole = requireStake && !hasRole;\n\n    // --- dryRun: perform NO writes. Simulate registerWithProof only if already staked (else it reverts\n    // on the missing stake, which is expected and not an error in a dry run). ---\n    if (dryRun) {\n        const effNow = requireStake ? await regRead.getEffectiveStake({ user: operator, roleId: ROLE_DVT }) : 0n;\n        let registerSimulated = false;\n        if (!requireStake || (hasRole && effNow >= minStake)) {\n            try {\n                await publicClient.simulateContract({\n                    address: validator,\n                    abi: AAStarBLSAlgorithmABI as any,\n                    functionName: 'registerWithProof',\n                    args: [pop.publicKey, pop.popPoint, pop.popSig],\n                    account: operatorWallet.account as Account,\n                });\n                registerSimulated = true;\n            } catch {\n                registerSimulated = false;\n            }\n        }\n        return {\n            nodeId, publicKey, operator,\n            alreadyRegistered: false, registered: false, staked: false,\n            effectiveStake: effNow, minStake, hashes,\n            plan: {\n                requireStake, needGToken, wouldFundEth, wouldFundGToken,\n                wouldApprove, wouldRegisterRole, registerSimulated,\n            },\n        };\n    }\n\n    // --- 4. fund operator gas (owner 代付) — before any operator-signed tx ---\n    if (wouldFundEth > 0n) {\n        if (!funderWallet?.account) {\n            throw new Error(\n                `onboardDvtNode: operator ETH ${formatEther(opEth)} < required ${formatEther(minOperatorEth)} ` +\n                `and no funderWallet was provided — fund the operator or pass funderWallet.`,\n            );\n        }\n        const h = await funderWallet.sendTransaction({\n            account: funderWallet.account,\n            chain: funderWallet.chain ?? null,\n            to: operator,\n            value: wouldFundEth,\n        });\n        await waitSuccess('fundEth', h);\n        hashes.fundEth = h;\n    }\n\n    // --- 5. stake ROLE_DVT (fund GToken → approve → registerRole) ---\n    let staked = false;\n    let effectiveStake = 0n;\n    if (requireStake) {\n        if (wouldFundGToken > 0n) {\n            if (!funderWallet?.account) {\n                throw new Error(\n                    `onboardDvtNode: operator GToken ${formatEther(opGt)} < required ${formatEther(needGToken)} ` +\n                    `and no funderWallet was provided — fund the operator or pass funderWallet.`,\n                );\n            }\n            const gtFunder = tokenActions()(funderWallet);\n            const h = await gtFunder.transfer({ token: gToken, to: operator, amount: wouldFundGToken });\n            await waitSuccess('fundGToken', h);\n            hashes.fundGToken = h;\n        }\n\n        if (wouldApprove) {\n            // Approve 2x headroom so a later top-up does not force a re-approve.\n            const h = await gtOp.approve({ token: gToken, spender: staking, amount: needGToken * 2n });\n            await waitSuccess('approve', h);\n            hashes.approve = h;\n        }\n\n        if (wouldRegisterRole) {\n            const h = await regOp.registerRole({ roleId: ROLE_DVT, user: operator, data: '0x' });\n            await waitSuccess('registerRole', h);\n            hashes.registerRole = h;\n            staked = true;\n        }\n\n        effectiveStake = await regRead.getEffectiveStake({ user: operator, roleId: ROLE_DVT });\n        if (effectiveStake < minStake) {\n            throw new Error(\n                `onboardDvtNode: effectiveStake ${formatEther(effectiveStake)} < minStake ${formatEther(minStake)} ` +\n                `after registerRole — aborting before registerWithProof.`,\n            );\n        }\n    }\n\n    // --- 6. preflight simulate (throws on any revert before spending register gas) ---\n    await publicClient.simulateContract({\n        address: validator,\n        abi: AAStarBLSAlgorithmABI as any,\n        functionName: 'registerWithProof',\n        args: [pop.publicKey, pop.popPoint, pop.popSig],\n        account: operatorWallet.account as Account,\n    });\n\n    // --- 7. registerWithProof + assert ---\n    const registerHash = await dvtOp.registerWithProof({\n        publicKey: pop.publicKey,\n        popPoint: pop.popPoint,\n        popSig: pop.popSig,\n    });\n    await waitSuccess('register', registerHash);\n    hashes.register = registerHash;\n\n    const isReg = await dvtRead.isRegistered({ nodeId });\n    const owner = await dvtRead.nodeOperator({ nodeId });\n    if (!isReg || owner.toLowerCase() !== operator.toLowerCase()) {\n        throw new Error(\n            `onboardDvtNode: post-condition failed — isRegistered=${isReg}, nodeOperator=${owner} (expected ${operator}).`,\n        );\n    }\n\n    return {\n        nodeId, publicKey, operator,\n        alreadyRegistered: false, registered: true, staked,\n        effectiveStake, minStake, hashes,\n    };\n}\n","import { type Account, type Hex, isHex } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\n/**\n * Node-only resolution of an **operator/funder EOA signer** for the DVT onboarding flow from the two\n * key sources DVT `register-node.mjs` supports: a raw private key held in an env var, and a\n * `forge cast wallet` account/keystore. This exists so an operator can reuse an existing `cast wallet`\n * setup instead of pasting a bare private key.\n *\n * NOTE — scope: `cast wallet` manages secp256k1 **Ethereum** keys only. The DVT node's **BLS** secret key\n * (which generates the public key being registered) cannot live in a cast wallet; supply it as\n * `blsSecretKey` hex (e.g. from its own env var) to {@link onboardDvtNode}.\n *\n * SECURITY: the `cast` path decrypts the keystore and reads the raw private key into this process's memory\n * so viem can sign transactions. Only run it on a host the operator controls. Prefer the `env` path in CI.\n * The keystore password is passed to `cast` via a MINIMAL child env (`ETH_PASSWORD`) — never on argv (which\n * is visible in `ps`) — and the child receives only `PATH`/`HOME`/`FOUNDRY_DIR`, not the parent's full env.\n */\nexport type EoaKeySource =\n    | { type: 'privateKey'; privateKey: Hex }\n    | {\n          /**\n           * Read the private key from an environment variable. Without `var`, the first non-empty of\n           * `OPERATOR_PRIVATE_KEY`, `ETH_PRIVATE_KEY`, `PRIVATE_KEY` is used.\n           */\n          type: 'env';\n          var?: string;\n      }\n    | {\n          /**\n           * Export the key via `cast wallet private-key <args>` (Foundry). `args` mirrors the DVT script's\n           * `CAST_WALLET_ARGS`, e.g. `['--account', 'dvt-op']` or `['--keystore', './ks.json']`. A `password`,\n           * when given, is passed to cast via the `ETH_PASSWORD` child env var (NOT argv) so keystore\n           * decryption is non-interactive without exposing the password in the process list.\n           */\n          type: 'cast';\n          args: string[];\n          password?: string;\n      };\n\nconst ENV_KEY_FALLBACKS = ['OPERATOR_PRIVATE_KEY', 'ETH_PRIVATE_KEY', 'PRIVATE_KEY'] as const;\n\n/** Normalize a hex private key to a `0x`-prefixed 32-byte value, throwing on anything malformed. */\nfunction normalizePrivateKey(raw: string, origin: string): Hex {\n    const trimmed = raw.trim();\n    const hex = (trimmed.startsWith('0x') ? trimmed : `0x${trimmed}`) as Hex;\n    if (!isHex(hex) || hex.length !== 66) {\n        throw new Error(`resolveEoaPrivateKey: ${origin} is not a 32-byte hex private key`);\n    }\n    return hex;\n}\n\n/** Resolve the raw private key hex from an {@link EoaKeySource}. Node-only for the `cast` source. */\nexport async function resolveEoaPrivateKey(source: EoaKeySource): Promise<Hex> {\n    if (source.type === 'privateKey') {\n        return normalizePrivateKey(source.privateKey, 'privateKey');\n    }\n\n    if (source.type === 'env') {\n        const names = source.var ? [source.var] : ENV_KEY_FALLBACKS;\n        for (const name of names) {\n            const val = process.env[name];\n            if (val && val.trim()) return normalizePrivateKey(val, `env ${name}`);\n        }\n        throw new Error(\n            `resolveEoaPrivateKey: no private key in env (${names.join(', ')})`,\n        );\n    }\n\n    // cast: `cast wallet private-key <args>`. This is a Node-only path. Build the module specifier at\n    // RUNTIME (Array.join — which esbuild does NOT constant-fold) so a browser bundler of\n    // @aastar/sdk/operator (which never calls this cast path) does not statically see / externalize\n    // `node:child_process` and fail the build. The magic comments tell Vite/webpack to leave it alone.\n    const nodeChildProcess = ['node', 'child_process'].join(':');\n    const { execFileSync } = (await import(/* @vite-ignore */ /* webpackIgnore: true */ nodeChildProcess)) as typeof import('node:child_process');\n    const args = ['wallet', 'private-key', ...source.args];\n    // Minimal child env: only what cast needs to locate/decrypt a keystore. The password goes through\n    // ETH_PASSWORD (never argv → not visible in `ps`); the parent's other secrets are NOT forwarded.\n    const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: process.env.HOME };\n    if (process.env.FOUNDRY_DIR) env.FOUNDRY_DIR = process.env.FOUNDRY_DIR;\n    if (source.password) env.ETH_PASSWORD = source.password;\n    let out: string;\n    try {\n        out = execFileSync('cast', args, { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'] });\n    } catch (e) {\n        const err = e as { stderr?: Buffer | string; message?: string };\n        const stderr = err.stderr ? err.stderr.toString() : (err.message ?? '');\n        throw new Error(`resolveEoaPrivateKey: \\`cast wallet private-key\\` failed — ${stderr.trim()}`);\n    }\n    // cast prints the key (0x + 64 hex), possibly with surrounding whitespace/log lines; take the last hex token.\n    const match = out.match(/0x[0-9a-fA-F]{64}/);\n    if (!match) throw new Error('resolveEoaPrivateKey: could not parse a private key from `cast` output');\n    return normalizePrivateKey(match[0], 'cast output');\n}\n\n/** Resolve an {@link EoaKeySource} into a viem {@link Account} ready to build a WalletClient. */\nexport async function resolveEoaAccount(source: EoaKeySource): Promise<Account> {\n    return privateKeyToAccount(await resolveEoaPrivateKey(source));\n}\n","import { type Hex, keccak256 } from 'viem';\nimport { dvtPopPoint, encodeG1Point, verifyDvtPop, type DvtPop } from '@aastar/core';\n\n/**\n * KMS-TEE Proof-of-Possession signer for a **key-less** DVT node — the CC-37 `/pop` contract.\n *\n * For a node whose BLS secret key never leaves the TEE, the SDK cannot run {@link buildDvtPop} locally.\n * KMS exposes `POST {url}/pop {node_id | publicKey} → {publicKey, popPoint, popSig}` where the TEE signs the\n * node's OWN 128-byte EIP-2537 public key (`popPoint = hashToCurve(publicKey, BLS_POP_DST)`, `popSig =\n * sk·popPoint`) — the caller supplies no message, so it is not a signing oracle. This returns a `popSigner`\n * callback you hand straight to {@link onboardDvtNode}.\n *\n * ## Trust model — READ THIS\n * The node the operator will register is `nodeId = keccak256(publicKey)`, where `publicKey` comes from the\n * `/pop` RESPONSE. `_verifyPoP` (and {@link verifyDvtPop} here) only prove the responder knows the `sk`\n * behind THAT key — a compromised KMS or a MITM can return a self-consistent tuple for an ATTACKER'S key,\n * and the operator would stake + register the attacker's node. The ONLY defence is to **pin the expected\n * public key**: pass `publicKey`, and the signer rejects any response whose key differs. If you address by\n * `nodeId` alone (no `publicKey`), you are trusting the KMS's `node_id → key` mapping — acceptable only for\n * a KMS you fully control (e.g. your own board loopback). Prefer passing the node's known `publicKey`.\n *\n * On every response the signer additionally: normalizes/validates `publicKey` to 128-byte EIP-2537,\n * recomputes `popPoint = hashToCurve(publicKey, BLS_POP_DST)` and rejects a mismatch (enforces the RFC\n * convention), runs the {@link verifyDvtPop} pairing (points on-curve/non-infinity + `popSig = sk·popPoint`)\n * so a bad tuple fails HERE rather than after stake, and derives `nodeId` locally (never from the response).\n */\nexport interface KmsPopSignerOptions {\n    /** KMS base URL, e.g. `http://127.0.0.1:3100` (board loopback) — `/pop` is appended. Treat as trusted config. */\n    url: string;\n    /** KMS-side node identifier the TEE maps to its sealed key. Provide this and/or {@link publicKey}. */\n    nodeId?: string;\n    /**\n     * The node's EXPECTED public key. Strongly recommended: when set, the signer pins it and rejects a\n     * response for any other key — the only defence against a KMS/MITM key substitution (see trust model).\n     */\n    publicKey?: Hex;\n    /** `X-Signer-Token` (same token as the KMS BLS `/sign`), if the endpoint requires it. */\n    token?: string;\n    /** Injected fetch (tests / non-browser runtimes). Defaults to the global `fetch`. */\n    fetchImpl?: typeof fetch;\n    /**\n     * Opt IN to the UNPINNED path — addressing by `nodeId` with NO expected {@link publicKey} to pin\n     * against. This trusts the KMS's `node_id → key` mapping completely: a compromised KMS/MITM can make\n     * you register an attacker's node (see trust model). Only acceptable for a KMS you fully control. When\n     * `publicKey` is omitted and this is not `true`, the signer throws rather than silently trusting.\n     */\n    allowUnpinnedKmsKey?: boolean;\n}\n\ninterface KmsPopResponse {\n    publicKey: Hex;\n    popPoint: Hex;\n    popSig: Hex;\n}\n\n/** Build a `popSigner` for {@link onboardDvtNode} that fetches a PoP from the KMS-TEE `/pop` endpoint. */\nexport function kmsPopSigner(opts: KmsPopSignerOptions): () => Promise<DvtPop> {\n    if (!opts.url) throw new Error('kmsPopSigner: url is required');\n    if (!opts.nodeId && !opts.publicKey) throw new Error('kmsPopSigner: provide nodeId and/or publicKey');\n    // Safe by default: without an expected publicKey to pin, the KMS key mapping is trusted blindly —\n    // require an explicit opt-in rather than silently exposing the key-substitution attack.\n    if (!opts.publicKey && !opts.allowUnpinnedKmsKey) {\n        throw new Error(\n            'kmsPopSigner: no expected `publicKey` to pin against — a compromised KMS could substitute an ' +\n            \"attacker's key. Pass the node's expected `publicKey`, or set `allowUnpinnedKmsKey: true` to \" +\n            'deliberately trust the KMS node_id→key mapping (only for a KMS you fully control).',\n        );\n    }\n    const doFetch = opts.fetchImpl ?? globalThis.fetch;\n    if (!doFetch) throw new Error('kmsPopSigner: no fetch implementation available (pass opts.fetchImpl)');\n    // Normalize the pinned key once up front (throws on a malformed input).\n    const pinnedKey = opts.publicKey ? encodeG1Point(opts.publicKey) : undefined;\n\n    return async () => {\n        const body: Record<string, string> = {};\n        if (opts.nodeId) body.node_id = opts.nodeId;\n        if (opts.publicKey) body.publicKey = opts.publicKey;\n        const res = await doFetch(`${opts.url.replace(/\\/$/, '')}/pop`, {\n            method: 'POST',\n            headers: { 'content-type': 'application/json', ...(opts.token ? { 'X-Signer-Token': opts.token } : {}) },\n            body: JSON.stringify(body),\n        });\n        if (!res.ok) {\n            throw new Error(`kmsPopSigner: KMS /pop returned HTTP ${res.status} (is the endpoint live? — CC-37)`);\n        }\n        const j = (await res.json()) as Partial<KmsPopResponse>;\n        if (!j.publicKey || !j.popPoint || !j.popSig) {\n            throw new Error('kmsPopSigner: KMS /pop response missing publicKey/popPoint/popSig');\n        }\n        // Normalize/validate the response pubkey to canonical 128-byte EIP-2537 (throws on a malformed blob).\n        const publicKey = encodeG1Point(j.publicKey);\n\n        // KEY PIN (the substitution defence): the response MUST be for the expected key, if one was given.\n        if (pinnedKey && publicKey.toLowerCase() !== pinnedKey.toLowerCase()) {\n            throw new Error(\n                'kmsPopSigner: KMS /pop returned a different publicKey than the one pinned — refusing to submit ' +\n                '(possible key substitution by a compromised KMS or MITM).',\n            );\n        }\n        // Enforce the RFC convention: popPoint must be hashToCurve(publicKey, BLS_POP_DST). No secret needed.\n        if (dvtPopPoint(publicKey).toLowerCase() !== j.popPoint.toLowerCase()) {\n            throw new Error(\n                'kmsPopSigner: KMS popPoint != hashToCurve(publicKey, BLS_POP_DST) — refusing to submit ' +\n                '(KMS PoP is inconsistent with the SDK golden convention).',\n            );\n        }\n        // Full pairing check (points valid + popSig = sk·popPoint) — fails HERE, before any stake/gas.\n        verifyDvtPop({ publicKey, popPoint: j.popPoint, popSig: j.popSig });\n\n        // nodeId is derived locally, never trusted from the response.\n        return { publicKey, popPoint: j.popPoint, popSig: j.popSig, nodeId: keccak256(publicKey) };\n    };\n}\n"]}